1//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file provides Sema routines for C++ overloading.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Sema/Overload.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/CXXInheritance.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/AST/TypeOrdering.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Basic/DiagnosticOptions.h"
23#include "clang/Basic/PartialDiagnostic.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
30#include "llvm/ADT/DenseSet.h"
31#include "llvm/ADT/Optional.h"
32#include "llvm/ADT/STLExtras.h"
33#include "llvm/ADT/SmallPtrSet.h"
34#include "llvm/ADT/SmallString.h"
35#include <algorithm>
36#include <cstdlib>
37
38using namespace clang;
39using namespace sema;
40
41static bool functionHasPassObjectSizeParams(const FunctionDecl *FD) {
42 return llvm::any_of(FD->parameters(), [](const ParmVarDecl *P) {
43 return P->hasAttr<PassObjectSizeAttr>();
44 });
45}
46
47/// A convenience routine for creating a decayed reference to a function.
48static ExprResult
49CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
50 const Expr *Base, bool HadMultipleCandidates,
51 SourceLocation Loc = SourceLocation(),
52 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
53 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
54 return ExprError();
55 // If FoundDecl is different from Fn (such as if one is a template
56 // and the other a specialization), make sure DiagnoseUseOfDecl is
57 // called on both.
58 // FIXME: This would be more comprehensively addressed by modifying
59 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
60 // being used.
61 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
62 return ExprError();
63 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
64 S.ResolveExceptionSpec(Loc, FPT);
65 DeclRefExpr *DRE = new (S.Context)
66 DeclRefExpr(S.Context, Fn, false, Fn->getType(), VK_LValue, Loc, LocInfo);
67 if (HadMultipleCandidates)
68 DRE->setHadMultipleCandidates(true);
69
70 S.MarkDeclRefReferenced(DRE, Base);
71 return S.ImpCastExprToType(DRE, S.Context.getPointerType(DRE->getType()),
72 CK_FunctionToPointerDecay);
73}
74
75static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
76 bool InOverloadResolution,
77 StandardConversionSequence &SCS,
78 bool CStyle,
79 bool AllowObjCWritebackConversion);
80
81static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
82 QualType &ToType,
83 bool InOverloadResolution,
84 StandardConversionSequence &SCS,
85 bool CStyle);
86static OverloadingResult
87IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
88 UserDefinedConversionSequence& User,
89 OverloadCandidateSet& Conversions,
90 bool AllowExplicit,
91 bool AllowObjCConversionOnExplicit);
92
93
94static ImplicitConversionSequence::CompareKind
95CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareQualificationConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104static ImplicitConversionSequence::CompareKind
105CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
106 const StandardConversionSequence& SCS1,
107 const StandardConversionSequence& SCS2);
108
109/// GetConversionRank - Retrieve the implicit conversion rank
110/// corresponding to the given implicit conversion kind.
111ImplicitConversionRank clang::GetConversionRank(ImplicitConversionKind Kind) {
112 static const ImplicitConversionRank
113 Rank[(int)ICK_Num_Conversion_Kinds] = {
114 ICR_Exact_Match,
115 ICR_Exact_Match,
116 ICR_Exact_Match,
117 ICR_Exact_Match,
118 ICR_Exact_Match,
119 ICR_Exact_Match,
120 ICR_Promotion,
121 ICR_Promotion,
122 ICR_Promotion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
127 ICR_Conversion,
128 ICR_Conversion,
129 ICR_Conversion,
130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_OCL_Scalar_Widening,
134 ICR_Complex_Real_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Writeback_Conversion,
138 ICR_Exact_Match, // NOTE(gbiv): This may not be completely right --
139 // it was omitted by the patch that added
140 // ICK_Zero_Event_Conversion
141 ICR_C_Conversion,
142 ICR_C_Conversion_Extension
143 };
144 return Rank[(int)Kind];
145}
146
147/// GetImplicitConversionName - Return the name of this kind of
148/// implicit conversion.
149static const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
150 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
151 "No conversion",
152 "Lvalue-to-rvalue",
153 "Array-to-pointer",
154 "Function-to-pointer",
155 "Function pointer conversion",
156 "Qualification",
157 "Integral promotion",
158 "Floating point promotion",
159 "Complex promotion",
160 "Integral conversion",
161 "Floating conversion",
162 "Complex conversion",
163 "Floating-integral conversion",
164 "Pointer conversion",
165 "Pointer-to-member conversion",
166 "Boolean conversion",
167 "Compatible-types conversion",
168 "Derived-to-base conversion",
169 "Vector conversion",
170 "Vector splat",
171 "Complex-real conversion",
172 "Block Pointer conversion",
173 "Transparent Union Conversion",
174 "Writeback conversion",
175 "OpenCL Zero Event Conversion",
176 "C specific type conversion",
177 "Incompatible pointer conversion"
178 };
179 return Name[Kind];
180}
181
182/// StandardConversionSequence - Set the standard conversion
183/// sequence to the identity conversion.
184void StandardConversionSequence::setAsIdentityConversion() {
185 First = ICK_Identity;
186 Second = ICK_Identity;
187 Third = ICK_Identity;
188 DeprecatedStringLiteralToCharPtr = false;
189 QualificationIncludesObjCLifetime = false;
190 ReferenceBinding = false;
191 DirectBinding = false;
192 IsLvalueReference = true;
193 BindsToFunctionLvalue = false;
194 BindsToRvalue = false;
195 BindsImplicitObjectArgumentWithoutRefQualifier = false;
196 ObjCLifetimeConversionBinding = false;
197 IncompatibleCHERIConversion = false;
198 CopyConstructor = nullptr;
199}
200
201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
217/// used as part of the ranking of standard conversion sequences
218/// (C++ 13.3.3.2p4).
219bool StandardConversionSequence::isPointerConversionToBool() const {
220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
224 if (getToType(1)->isBooleanType() &&
225 (getFromType()->isPointerType() ||
226 getFromType()->isMemberPointerType() ||
227 getFromType()->isObjCObjectPointerType() ||
228 getFromType()->isBlockPointerType() ||
229 getFromType()->isNullPtrType() ||
230 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
231 return true;
232
233 return false;
234}
235
236/// isPointerConversionToVoidPointer - Determines whether this
237/// conversion is a conversion of a pointer to a void pointer. This is
238/// used as part of the ranking of standard conversion sequences (C++
239/// 13.3.3.2p4).
240bool
241StandardConversionSequence::
242isPointerConversionToVoidPointer(ASTContext& Context) const {
243 QualType FromType = getFromType();
244 QualType ToType = getToType(1);
245
246 // Note that FromType has not necessarily been transformed by the
247 // array-to-pointer implicit conversion, so check for its presence
248 // and redo the conversion to get a pointer.
249 if (First == ICK_Array_To_Pointer)
250 FromType = Context.getArrayDecayedType(FromType);
251
252 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
253 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
254 return ToPtrType->getPointeeType()->isVoidType();
255
256 return false;
257}
258
259/// Skip any implicit casts which could be either part of a narrowing conversion
260/// or after one in an implicit conversion.
261static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
262 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
263 switch (ICE->getCastKind()) {
264 case CK_NoOp:
265 case CK_IntegralCast:
266 case CK_IntegralToBoolean:
267 case CK_IntegralToFloating:
268 case CK_BooleanToSignedIntegral:
269 case CK_FloatingToIntegral:
270 case CK_FloatingToBoolean:
271 case CK_FloatingCast:
272 Converted = ICE->getSubExpr();
273 continue;
274
275 default:
276 return Converted;
277 }
278 }
279
280 return Converted;
281}
282
283/// Check if this standard conversion sequence represents a narrowing
284/// conversion, according to C++11 [dcl.init.list]p7.
285///
286/// \param Ctx The AST context.
287/// \param Converted The result of applying this standard conversion sequence.
288/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
289/// value of the expression prior to the narrowing conversion.
290/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
291/// type of the expression prior to the narrowing conversion.
292/// \param IgnoreFloatToIntegralConversion If true type-narrowing conversions
293/// from floating point types to integral types should be ignored.
294NarrowingKind StandardConversionSequence::getNarrowingKind(
295 ASTContext &Ctx, const Expr *Converted, APValue &ConstantValue,
296 QualType &ConstantType, bool IgnoreFloatToIntegralConversion) const {
297 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
298
299 // C++11 [dcl.init.list]p7:
300 // A narrowing conversion is an implicit conversion ...
301 QualType FromType = getToType(0);
302 QualType ToType = getToType(1);
303
304 // A conversion to an enumeration type is narrowing if the conversion to
305 // the underlying type is narrowing. This only arises for expressions of
306 // the form 'Enum{init}'.
307 if (auto *ET = ToType->getAs<EnumType>())
308 ToType = ET->getDecl()->getIntegerType();
309
310 // Converting from capability to pointer/integral is always narrowing
311 if (FromType->isCHERICapabilityType(Ctx) && !ToType->isCHERICapabilityType(Ctx))
312 return NK_Type_Narrowing;
313
314 switch (Second) {
315 // 'bool' is an integral type; dispatch to the right place to handle it.
316 case ICK_Boolean_Conversion:
317 if (FromType->isRealFloatingType())
318 goto FloatingIntegralConversion;
319 if (FromType->isIntegralOrUnscopedEnumerationType())
320 goto IntegralConversion;
321 // Boolean conversions can be from pointers and pointers to members
322 // [conv.bool], and those aren't considered narrowing conversions.
323 return NK_Not_Narrowing;
324
325 // -- from a floating-point type to an integer type, or
326 //
327 // -- from an integer type or unscoped enumeration type to a floating-point
328 // type, except where the source is a constant expression and the actual
329 // value after conversion will fit into the target type and will produce
330 // the original value when converted back to the original type, or
331 case ICK_Floating_Integral:
332 FloatingIntegralConversion:
333 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
334 return NK_Type_Narrowing;
335 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
336 ToType->isRealFloatingType()) {
337 if (IgnoreFloatToIntegralConversion)
338 return NK_Not_Narrowing;
339 llvm::APSInt IntConstantValue;
340 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
341 assert(Initializer && "Unknown conversion expression");
342
343 // If it's value-dependent, we can't tell whether it's narrowing.
344 if (Initializer->isValueDependent())
345 return NK_Dependent_Narrowing;
346
347 if (Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
348 // Convert the integer to the floating type.
349 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
350 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
351 llvm::APFloat::rmNearestTiesToEven);
352 // And back.
353 llvm::APSInt ConvertedValue = IntConstantValue;
354 bool ignored;
355 Result.convertToInteger(ConvertedValue,
356 llvm::APFloat::rmTowardZero, &ignored);
357 // If the resulting value is different, this was a narrowing conversion.
358 if (IntConstantValue != ConvertedValue) {
359 ConstantValue = APValue(IntConstantValue);
360 ConstantType = Initializer->getType();
361 return NK_Constant_Narrowing;
362 }
363 } else {
364 // Variables are always narrowings.
365 return NK_Variable_Narrowing;
366 }
367 }
368 return NK_Not_Narrowing;
369
370 // -- from long double to double or float, or from double to float, except
371 // where the source is a constant expression and the actual value after
372 // conversion is within the range of values that can be represented (even
373 // if it cannot be represented exactly), or
374 case ICK_Floating_Conversion:
375 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
376 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
377 // FromType is larger than ToType.
378 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
379
380 // If it's value-dependent, we can't tell whether it's narrowing.
381 if (Initializer->isValueDependent())
382 return NK_Dependent_Narrowing;
383
384 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
385 // Constant!
386 assert(ConstantValue.isFloat());
387 llvm::APFloat FloatVal = ConstantValue.getFloat();
388 // Convert the source value into the target type.
389 bool ignored;
390 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
391 Ctx.getFloatTypeSemantics(ToType),
392 llvm::APFloat::rmNearestTiesToEven, &ignored);
393 // If there was no overflow, the source value is within the range of
394 // values that can be represented.
395 if (ConvertStatus & llvm::APFloat::opOverflow) {
396 ConstantType = Initializer->getType();
397 return NK_Constant_Narrowing;
398 }
399 } else {
400 return NK_Variable_Narrowing;
401 }
402 }
403 return NK_Not_Narrowing;
404
405 // -- from an integer type or unscoped enumeration type to an integer type
406 // that cannot represent all the values of the original type, except where
407 // the source is a constant expression and the actual value after
408 // conversion will fit into the target type and will produce the original
409 // value when converted back to the original type.
410 case ICK_Integral_Conversion:
411 IntegralConversion: {
412 assert(FromType->isIntegralOrUnscopedEnumerationType());
413 assert(ToType->isIntegralOrUnscopedEnumerationType());
414 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
415 const unsigned FromWidth = Ctx.getIntWidth(FromType);
416 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
417 const unsigned ToWidth = Ctx.getIntWidth(ToType);
418
419 if (FromWidth > ToWidth ||
420 (FromWidth == ToWidth && FromSigned != ToSigned) ||
421 (FromSigned && !ToSigned)) {
422 // Not all values of FromType can be represented in ToType.
423 llvm::APSInt InitializerValue;
424 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
425
426 // If it's value-dependent, we can't tell whether it's narrowing.
427 if (Initializer->isValueDependent())
428 return NK_Dependent_Narrowing;
429
430 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
431 // Such conversions on variables are always narrowing.
432 return NK_Variable_Narrowing;
433 }
434 bool Narrowing = false;
435 if (FromWidth < ToWidth) {
436 // Negative -> unsigned is narrowing. Otherwise, more bits is never
437 // narrowing.
438 if (InitializerValue.isSigned() && InitializerValue.isNegative())
439 Narrowing = true;
440 } else {
441 // Add a bit to the InitializerValue so we don't have to worry about
442 // signed vs. unsigned comparisons.
443 InitializerValue = InitializerValue.extend(
444 InitializerValue.getBitWidth() + 1);
445 // Convert the initializer to and from the target width and signed-ness.
446 llvm::APSInt ConvertedValue = InitializerValue;
447 ConvertedValue = ConvertedValue.trunc(ToWidth);
448 ConvertedValue.setIsSigned(ToSigned);
449 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
450 ConvertedValue.setIsSigned(InitializerValue.isSigned());
451 // If the result is different, this was a narrowing conversion.
452 if (ConvertedValue != InitializerValue)
453 Narrowing = true;
454 }
455 if (Narrowing) {
456 ConstantType = Initializer->getType();
457 ConstantValue = APValue(InitializerValue);
458 return NK_Constant_Narrowing;
459 }
460 }
461 return NK_Not_Narrowing;
462 }
463
464 default:
465 // Other kinds of conversions are not narrowings.
466 return NK_Not_Narrowing;
467 }
468}
469
470/// dump - Print this standard conversion sequence to standard
471/// error. Useful for debugging overloading issues.
472LLVM_DUMP_METHOD void StandardConversionSequence::dump() const {
473 raw_ostream &OS = llvm::errs();
474 bool PrintedSomething = false;
475 if (First != ICK_Identity) {
476 OS << GetImplicitConversionName(First);
477 PrintedSomething = true;
478 }
479
480 if (Second != ICK_Identity) {
481 if (PrintedSomething) {
482 OS << " -> ";
483 }
484 OS << GetImplicitConversionName(Second);
485
486 if (CopyConstructor) {
487 OS << " (by copy constructor)";
488 } else if (DirectBinding) {
489 OS << " (direct reference binding)";
490 } else if (ReferenceBinding) {
491 OS << " (reference binding)";
492 }
493 PrintedSomething = true;
494 }
495
496 if (Third != ICK_Identity) {
497 if (PrintedSomething) {
498 OS << " -> ";
499 }
500 OS << GetImplicitConversionName(Third);
501 PrintedSomething = true;
502 }
503
504 if (!PrintedSomething) {
505 OS << "No conversions required";
506 }
507}
508
509/// dump - Print this user-defined conversion sequence to standard
510/// error. Useful for debugging overloading issues.
511void UserDefinedConversionSequence::dump() const {
512 raw_ostream &OS = llvm::errs();
513 if (Before.First || Before.Second || Before.Third) {
514 Before.dump();
515 OS << " -> ";
516 }
517 if (ConversionFunction)
518 OS << '\'' << *ConversionFunction << '\'';
519 else
520 OS << "aggregate initialization";
521 if (After.First || After.Second || After.Third) {
522 OS << " -> ";
523 After.dump();
524 }
525}
526
527/// dump - Print this implicit conversion sequence to standard
528/// error. Useful for debugging overloading issues.
529void ImplicitConversionSequence::dump() const {
530 raw_ostream &OS = llvm::errs();
531 if (isStdInitializerListElement())
532 OS << "Worst std::initializer_list element conversion: ";
533 switch (ConversionKind) {
534 case StandardConversion:
535 OS << "Standard conversion: ";
536 Standard.dump();
537 break;
538 case UserDefinedConversion:
539 OS << "User-defined conversion: ";
540 UserDefined.dump();
541 break;
542 case EllipsisConversion:
543 OS << "Ellipsis conversion";
544 break;
545 case AmbiguousConversion:
546 OS << "Ambiguous conversion";
547 break;
548 case BadConversion:
549 OS << "Bad conversion";
550 break;
551 }
552
553 OS << "\n";
554}
555
556void AmbiguousConversionSequence::construct() {
557 new (&conversions()) ConversionSet();
558}
559
560void AmbiguousConversionSequence::destruct() {
561 conversions().~ConversionSet();
562}
563
564void
565AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
566 FromTypePtr = O.FromTypePtr;
567 ToTypePtr = O.ToTypePtr;
568 new (&conversions()) ConversionSet(O.conversions());
569}
570
571namespace {
572 // Structure used by DeductionFailureInfo to store
573 // template argument information.
574 struct DFIArguments {
575 TemplateArgument FirstArg;
576 TemplateArgument SecondArg;
577 };
578 // Structure used by DeductionFailureInfo to store
579 // template parameter and template argument information.
580 struct DFIParamWithArguments : DFIArguments {
581 TemplateParameter Param;
582 };
583 // Structure used by DeductionFailureInfo to store template argument
584 // information and the index of the problematic call argument.
585 struct DFIDeducedMismatchArgs : DFIArguments {
586 TemplateArgumentList *TemplateArgs;
587 unsigned CallArgIndex;
588 };
589}
590
591/// Convert from Sema's representation of template deduction information
592/// to the form used in overload-candidate information.
593DeductionFailureInfo
594clang::MakeDeductionFailureInfo(ASTContext &Context,
595 Sema::TemplateDeductionResult TDK,
596 TemplateDeductionInfo &Info) {
597 DeductionFailureInfo Result;
598 Result.Result = static_cast<unsigned>(TDK);
599 Result.HasDiagnostic = false;
600 switch (TDK) {
601 case Sema::TDK_Invalid:
602 case Sema::TDK_InstantiationDepth:
603 case Sema::TDK_TooManyArguments:
604 case Sema::TDK_TooFewArguments:
605 case Sema::TDK_MiscellaneousDeductionFailure:
606 case Sema::TDK_CUDATargetMismatch:
607 Result.Data = nullptr;
608 break;
609
610 case Sema::TDK_Incomplete:
611 case Sema::TDK_InvalidExplicitArguments:
612 Result.Data = Info.Param.getOpaqueValue();
613 break;
614
615 case Sema::TDK_DeducedMismatch:
616 case Sema::TDK_DeducedMismatchNested: {
617 // FIXME: Should allocate from normal heap so that we can free this later.
618 auto *Saved = new (Context) DFIDeducedMismatchArgs;
619 Saved->FirstArg = Info.FirstArg;
620 Saved->SecondArg = Info.SecondArg;
621 Saved->TemplateArgs = Info.take();
622 Saved->CallArgIndex = Info.CallArgIndex;
623 Result.Data = Saved;
624 break;
625 }
626
627 case Sema::TDK_NonDeducedMismatch: {
628 // FIXME: Should allocate from normal heap so that we can free this later.
629 DFIArguments *Saved = new (Context) DFIArguments;
630 Saved->FirstArg = Info.FirstArg;
631 Saved->SecondArg = Info.SecondArg;
632 Result.Data = Saved;
633 break;
634 }
635
636 case Sema::TDK_IncompletePack:
637 // FIXME: It's slightly wasteful to allocate two TemplateArguments for this.
638 case Sema::TDK_Inconsistent:
639 case Sema::TDK_Underqualified: {
640 // FIXME: Should allocate from normal heap so that we can free this later.
641 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
642 Saved->Param = Info.Param;
643 Saved->FirstArg = Info.FirstArg;
644 Saved->SecondArg = Info.SecondArg;
645 Result.Data = Saved;
646 break;
647 }
648
649 case Sema::TDK_SubstitutionFailure:
650 Result.Data = Info.take();
651 if (Info.hasSFINAEDiagnostic()) {
652 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
653 SourceLocation(), PartialDiagnostic::NullDiagnostic());
654 Info.takeSFINAEDiagnostic(*Diag);
655 Result.HasDiagnostic = true;
656 }
657 break;
658
659 case Sema::TDK_Success:
660 case Sema::TDK_NonDependentConversionFailure:
661 llvm_unreachable("not a deduction failure");
662 }
663
664 return Result;
665}
666
667void DeductionFailureInfo::Destroy() {
668 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
669 case Sema::TDK_Success:
670 case Sema::TDK_Invalid:
671 case Sema::TDK_InstantiationDepth:
672 case Sema::TDK_Incomplete:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_InvalidExplicitArguments:
676 case Sema::TDK_CUDATargetMismatch:
677 case Sema::TDK_NonDependentConversionFailure:
678 break;
679
680 case Sema::TDK_IncompletePack:
681 case Sema::TDK_Inconsistent:
682 case Sema::TDK_Underqualified:
683 case Sema::TDK_DeducedMismatch:
684 case Sema::TDK_DeducedMismatchNested:
685 case Sema::TDK_NonDeducedMismatch:
686 // FIXME: Destroy the data?
687 Data = nullptr;
688 break;
689
690 case Sema::TDK_SubstitutionFailure:
691 // FIXME: Destroy the template argument list?
692 Data = nullptr;
693 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
694 Diag->~PartialDiagnosticAt();
695 HasDiagnostic = false;
696 }
697 break;
698
699 // Unhandled
700 case Sema::TDK_MiscellaneousDeductionFailure:
701 break;
702 }
703}
704
705PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
706 if (HasDiagnostic)
707 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
708 return nullptr;
709}
710
711TemplateParameter DeductionFailureInfo::getTemplateParameter() {
712 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
713 case Sema::TDK_Success:
714 case Sema::TDK_Invalid:
715 case Sema::TDK_InstantiationDepth:
716 case Sema::TDK_TooManyArguments:
717 case Sema::TDK_TooFewArguments:
718 case Sema::TDK_SubstitutionFailure:
719 case Sema::TDK_DeducedMismatch:
720 case Sema::TDK_DeducedMismatchNested:
721 case Sema::TDK_NonDeducedMismatch:
722 case Sema::TDK_CUDATargetMismatch:
723 case Sema::TDK_NonDependentConversionFailure:
724 return TemplateParameter();
725
726 case Sema::TDK_Incomplete:
727 case Sema::TDK_InvalidExplicitArguments:
728 return TemplateParameter::getFromOpaqueValue(Data);
729
730 case Sema::TDK_IncompletePack:
731 case Sema::TDK_Inconsistent:
732 case Sema::TDK_Underqualified:
733 return static_cast<DFIParamWithArguments*>(Data)->Param;
734
735 // Unhandled
736 case Sema::TDK_MiscellaneousDeductionFailure:
737 break;
738 }
739
740 return TemplateParameter();
741}
742
743TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
744 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
745 case Sema::TDK_Success:
746 case Sema::TDK_Invalid:
747 case Sema::TDK_InstantiationDepth:
748 case Sema::TDK_TooManyArguments:
749 case Sema::TDK_TooFewArguments:
750 case Sema::TDK_Incomplete:
751 case Sema::TDK_IncompletePack:
752 case Sema::TDK_InvalidExplicitArguments:
753 case Sema::TDK_Inconsistent:
754 case Sema::TDK_Underqualified:
755 case Sema::TDK_NonDeducedMismatch:
756 case Sema::TDK_CUDATargetMismatch:
757 case Sema::TDK_NonDependentConversionFailure:
758 return nullptr;
759
760 case Sema::TDK_DeducedMismatch:
761 case Sema::TDK_DeducedMismatchNested:
762 return static_cast<DFIDeducedMismatchArgs*>(Data)->TemplateArgs;
763
764 case Sema::TDK_SubstitutionFailure:
765 return static_cast<TemplateArgumentList*>(Data);
766
767 // Unhandled
768 case Sema::TDK_MiscellaneousDeductionFailure:
769 break;
770 }
771
772 return nullptr;
773}
774
775const TemplateArgument *DeductionFailureInfo::getFirstArg() {
776 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
777 case Sema::TDK_Success:
778 case Sema::TDK_Invalid:
779 case Sema::TDK_InstantiationDepth:
780 case Sema::TDK_Incomplete:
781 case Sema::TDK_TooManyArguments:
782 case Sema::TDK_TooFewArguments:
783 case Sema::TDK_InvalidExplicitArguments:
784 case Sema::TDK_SubstitutionFailure:
785 case Sema::TDK_CUDATargetMismatch:
786 case Sema::TDK_NonDependentConversionFailure:
787 return nullptr;
788
789 case Sema::TDK_IncompletePack:
790 case Sema::TDK_Inconsistent:
791 case Sema::TDK_Underqualified:
792 case Sema::TDK_DeducedMismatch:
793 case Sema::TDK_DeducedMismatchNested:
794 case Sema::TDK_NonDeducedMismatch:
795 return &static_cast<DFIArguments*>(Data)->FirstArg;
796
797 // Unhandled
798 case Sema::TDK_MiscellaneousDeductionFailure:
799 break;
800 }
801
802 return nullptr;
803}
804
805const TemplateArgument *DeductionFailureInfo::getSecondArg() {
806 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
807 case Sema::TDK_Success:
808 case Sema::TDK_Invalid:
809 case Sema::TDK_InstantiationDepth:
810 case Sema::TDK_Incomplete:
811 case Sema::TDK_IncompletePack:
812 case Sema::TDK_TooManyArguments:
813 case Sema::TDK_TooFewArguments:
814 case Sema::TDK_InvalidExplicitArguments:
815 case Sema::TDK_SubstitutionFailure:
816 case Sema::TDK_CUDATargetMismatch:
817 case Sema::TDK_NonDependentConversionFailure:
818 return nullptr;
819
820 case Sema::TDK_Inconsistent:
821 case Sema::TDK_Underqualified:
822 case Sema::TDK_DeducedMismatch:
823 case Sema::TDK_DeducedMismatchNested:
824 case Sema::TDK_NonDeducedMismatch:
825 return &static_cast<DFIArguments*>(Data)->SecondArg;
826
827 // Unhandled
828 case Sema::TDK_MiscellaneousDeductionFailure:
829 break;
830 }
831
832 return nullptr;
833}
834
835llvm::Optional<unsigned> DeductionFailureInfo::getCallArgIndex() {
836 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
837 case Sema::TDK_DeducedMismatch:
838 case Sema::TDK_DeducedMismatchNested:
839 return static_cast<DFIDeducedMismatchArgs*>(Data)->CallArgIndex;
840
841 default:
842 return llvm::None;
843 }
844}
845
846void OverloadCandidateSet::destroyCandidates() {
847 for (iterator i = begin(), e = end(); i != e; ++i) {
848 for (auto &C : i->Conversions)
849 C.~ImplicitConversionSequence();
850 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
851 i->DeductionFailure.Destroy();
852 }
853}
854
855void OverloadCandidateSet::clear(CandidateSetKind CSK) {
856 destroyCandidates();
857 SlabAllocator.Reset();
858 NumInlineBytesUsed = 0;
859 Candidates.clear();
860 Functions.clear();
861 Kind = CSK;
862}
863
864namespace {
865 class UnbridgedCastsSet {
866 struct Entry {
867 Expr **Addr;
868 Expr *Saved;
869 };
870 SmallVector<Entry, 2> Entries;
871
872 public:
873 void save(Sema &S, Expr *&E) {
874 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
875 Entry entry = { &E, E };
876 Entries.push_back(entry);
877 E = S.stripARCUnbridgedCast(E);
878 }
879
880 void restore() {
881 for (SmallVectorImpl<Entry>::iterator
882 i = Entries.begin(), e = Entries.end(); i != e; ++i)
883 *i->Addr = i->Saved;
884 }
885 };
886}
887
888/// checkPlaceholderForOverload - Do any interesting placeholder-like
889/// preprocessing on the given expression.
890///
891/// \param unbridgedCasts a collection to which to add unbridged casts;
892/// without this, they will be immediately diagnosed as errors
893///
894/// Return true on unrecoverable error.
895static bool
896checkPlaceholderForOverload(Sema &S, Expr *&E,
897 UnbridgedCastsSet *unbridgedCasts = nullptr) {
898 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
899 // We can't handle overloaded expressions here because overload
900 // resolution might reasonably tweak them.
901 if (placeholder->getKind() == BuiltinType::Overload) return false;
902
903 // If the context potentially accepts unbridged ARC casts, strip
904 // the unbridged cast and add it to the collection for later restoration.
905 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
906 unbridgedCasts) {
907 unbridgedCasts->save(S, E);
908 return false;
909 }
910
911 // Go ahead and check everything else.
912 ExprResult result = S.CheckPlaceholderExpr(E);
913 if (result.isInvalid())
914 return true;
915
916 E = result.get();
917 return false;
918 }
919
920 // Nothing to do.
921 return false;
922}
923
924/// checkArgPlaceholdersForOverload - Check a set of call operands for
925/// placeholders.
926static bool checkArgPlaceholdersForOverload(Sema &S,
927 MultiExprArg Args,
928 UnbridgedCastsSet &unbridged) {
929 for (unsigned i = 0, e = Args.size(); i != e; ++i)
930 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
931 return true;
932
933 return false;
934}
935
936/// Determine whether the given New declaration is an overload of the
937/// declarations in Old. This routine returns Ovl_Match or Ovl_NonFunction if
938/// New and Old cannot be overloaded, e.g., if New has the same signature as
939/// some function in Old (C++ 1.3.10) or if the Old declarations aren't
940/// functions (or function templates) at all. When it does return Ovl_Match or
941/// Ovl_NonFunction, MatchedDecl will point to the decl that New cannot be
942/// overloaded with. This decl may be a UsingShadowDecl on top of the underlying
943/// declaration.
944///
945/// Example: Given the following input:
946///
947/// void f(int, float); // #1
948/// void f(int, int); // #2
949/// int f(int, int); // #3
950///
951/// When we process #1, there is no previous declaration of "f", so IsOverload
952/// will not be used.
953///
954/// When we process #2, Old contains only the FunctionDecl for #1. By comparing
955/// the parameter types, we see that #1 and #2 are overloaded (since they have
956/// different signatures), so this routine returns Ovl_Overload; MatchedDecl is
957/// unchanged.
958///
959/// When we process #3, Old is an overload set containing #1 and #2. We compare
960/// the signatures of #3 to #1 (they're overloaded, so we do nothing) and then
961/// #3 to #2. Since the signatures of #3 and #2 are identical (return types of
962/// functions are not part of the signature), IsOverload returns Ovl_Match and
963/// MatchedDecl will be set to point to the FunctionDecl for #2.
964///
965/// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced into a class
966/// by a using declaration. The rules for whether to hide shadow declarations
967/// ignore some properties which otherwise figure into a function template's
968/// signature.
969Sema::OverloadKind
970Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
971 NamedDecl *&Match, bool NewIsUsingDecl) {
972 for (LookupResult::iterator I = Old.begin(), E = Old.end();
973 I != E; ++I) {
974 NamedDecl *OldD = *I;
975
976 bool OldIsUsingDecl = false;
977 if (isa<UsingShadowDecl>(OldD)) {
978 OldIsUsingDecl = true;
979
980 // We can always introduce two using declarations into the same
981 // context, even if they have identical signatures.
982 if (NewIsUsingDecl) continue;
983
984 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
985 }
986
987 // A using-declaration does not conflict with another declaration
988 // if one of them is hidden.
989 if ((OldIsUsingDecl || NewIsUsingDecl) && !isVisible(*I))
990 continue;
991
992 // If either declaration was introduced by a using declaration,
993 // we'll need to use slightly different rules for matching.
994 // Essentially, these rules are the normal rules, except that
995 // function templates hide function templates with different
996 // return types or template parameter lists.
997 bool UseMemberUsingDeclRules =
998 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
999 !New->getFriendObjectKind();
1000
1001 if (FunctionDecl *OldF = OldD->getAsFunction()) {
1002 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
1003 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
1004 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
1005 continue;
1006 }
1007
1008 if (!isa<FunctionTemplateDecl>(OldD) &&
1009 !shouldLinkPossiblyHiddenDecl(*I, New))
1010 continue;
1011
1012 Match = *I;
1013 return Ovl_Match;
1014 }
1015
1016 // Builtins that have custom typechecking or have a reference should
1017 // not be overloadable or redeclarable.
1018 if (!getASTContext().canBuiltinBeRedeclared(OldF)) {
1019 Match = *I;
1020 return Ovl_NonFunction;
1021 }
1022 } else if (isa<UsingDecl>(OldD) || isa<UsingPackDecl>(OldD)) {
1023 // We can overload with these, which can show up when doing
1024 // redeclaration checks for UsingDecls.
1025 assert(Old.getLookupKind() == LookupUsingDeclName);
1026 } else if (isa<TagDecl>(OldD)) {
1027 // We can always overload with tags by hiding them.
1028 } else if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(OldD)) {
1029 // Optimistically assume that an unresolved using decl will
1030 // overload; if it doesn't, we'll have to diagnose during
1031 // template instantiation.
1032 //
1033 // Exception: if the scope is dependent and this is not a class
1034 // member, the using declaration can only introduce an enumerator.
1035 if (UUD->getQualifier()->isDependent() && !UUD->isCXXClassMember()) {
1036 Match = *I;
1037 return Ovl_NonFunction;
1038 }
1039 } else {
1040 // (C++ 13p1):
1041 // Only function declarations can be overloaded; object and type
1042 // declarations cannot be overloaded.
1043 Match = *I;
1044 return Ovl_NonFunction;
1045 }
1046 }
1047
1048 // C++ [temp.friend]p1:
1049 // For a friend function declaration that is not a template declaration:
1050 // -- if the name of the friend is a qualified or unqualified template-id,
1051 // [...], otherwise
1052 // -- if the name of the friend is a qualified-id and a matching
1053 // non-template function is found in the specified class or namespace,
1054 // the friend declaration refers to that function, otherwise,
1055 // -- if the name of the friend is a qualified-id and a matching function
1056 // template is found in the specified class or namespace, the friend
1057 // declaration refers to the deduced specialization of that function
1058 // template, otherwise
1059 // -- the name shall be an unqualified-id [...]
1060 // If we get here for a qualified friend declaration, we've just reached the
1061 // third bullet. If the type of the friend is dependent, skip this lookup
1062 // until instantiation.
1063 if (New->getFriendObjectKind() && New->getQualifier() &&
1064 !New->getDescribedFunctionTemplate() &&
1065 !New->getDependentSpecializationInfo() &&
1066 !New->getType()->isDependentType()) {
1067 LookupResult TemplateSpecResult(LookupResult::Temporary, Old);
1068 TemplateSpecResult.addAllDecls(Old);
1069 if (CheckFunctionTemplateSpecialization(New, nullptr, TemplateSpecResult,
1070 /*QualifiedFriend*/true)) {
1071 New->setInvalidDecl();
1072 return Ovl_Overload;
1073 }
1074
1075 Match = TemplateSpecResult.getAsSingle<FunctionDecl>();
1076 return Ovl_Match;
1077 }
1078
1079 return Ovl_Overload;
1080}
1081
1082bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1083 bool UseMemberUsingDeclRules, bool ConsiderCudaAttrs) {
1084 // C++ [basic.start.main]p2: This function shall not be overloaded.
1085 if (New->isMain())
1086 return false;
1087
1088 // MSVCRT user defined entry points cannot be overloaded.
1089 if (New->isMSVCRTEntryPoint())
1090 return false;
1091
1092 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
1093 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
1094
1095 // C++ [temp.fct]p2:
1096 // A function template can be overloaded with other function templates
1097 // and with normal (non-template) functions.
1098 if ((OldTemplate == nullptr) != (NewTemplate == nullptr))
1099 return true;
1100
1101 // Is the function New an overload of the function Old?
1102 QualType OldQType = Context.getCanonicalType(Old->getType());
1103 QualType NewQType = Context.getCanonicalType(New->getType());
1104
1105 // Compare the signatures (C++ 1.3.10) of the two functions to
1106 // determine whether they are overloads. If we find any mismatch
1107 // in the signature, they are overloads.
1108
1109 // If either of these functions is a K&R-style function (no
1110 // prototype), then we consider them to have matching signatures.
1111 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1112 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1113 return false;
1114
1115 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1116 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
1117
1118 // The signature of a function includes the types of its
1119 // parameters (C++ 1.3.10), which includes the presence or absence
1120 // of the ellipsis; see C++ DR 357).
1121 if (OldQType != NewQType &&
1122 (OldType->getNumParams() != NewType->getNumParams() ||
1123 OldType->isVariadic() != NewType->isVariadic() ||
1124 !FunctionParamTypesAreEqual(OldType, NewType)))
1125 return true;
1126
1127 // C++ [temp.over.link]p4:
1128 // The signature of a function template consists of its function
1129 // signature, its return type and its template parameter list. The names
1130 // of the template parameters are significant only for establishing the
1131 // relationship between the template parameters and the rest of the
1132 // signature.
1133 //
1134 // We check the return type and template parameter lists for function
1135 // templates first; the remaining checks follow.
1136 //
1137 // However, we don't consider either of these when deciding whether
1138 // a member introduced by a shadow declaration is hidden.
1139 if (!UseMemberUsingDeclRules && NewTemplate &&
1140 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1141 OldTemplate->getTemplateParameters(),
1142 false, TPL_TemplateMatch) ||
1143 !Context.hasSameType(Old->getDeclaredReturnType(),
1144 New->getDeclaredReturnType())))
1145 return true;
1146
1147 // If the function is a class member, its signature includes the
1148 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
1149 //
1150 // As part of this, also check whether one of the member functions
1151 // is static, in which case they are not overloads (C++
1152 // 13.1p2). While not part of the definition of the signature,
1153 // this check is important to determine whether these functions
1154 // can be overloaded.
1155 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1156 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
1157 if (OldMethod && NewMethod &&
1158 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1159 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1160 if (!UseMemberUsingDeclRules &&
1161 (OldMethod->getRefQualifier() == RQ_None ||
1162 NewMethod->getRefQualifier() == RQ_None)) {
1163 // C++0x [over.load]p2:
1164 // - Member function declarations with the same name and the same
1165 // parameter-type-list as well as member function template
1166 // declarations with the same name, the same parameter-type-list, and
1167 // the same template parameter lists cannot be overloaded if any of
1168 // them, but not all, have a ref-qualifier (8.3.5).
1169 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1170 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1171 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1172 }
1173 return true;
1174 }
1175
1176 // We may not have applied the implicit const for a constexpr member
1177 // function yet (because we haven't yet resolved whether this is a static
1178 // or non-static member function). Add it now, on the assumption that this
1179 // is a redeclaration of OldMethod.
1180 auto OldQuals = OldMethod->getMethodQualifiers();
1181 auto NewQuals = NewMethod->getMethodQualifiers();
1182 if (!getLangOpts().CPlusPlus14 && NewMethod->isConstexpr() &&
1183 !isa<CXXConstructorDecl>(NewMethod))
1184 NewQuals.addConst();
1185 // We do not allow overloading based off of '__restrict'.
1186 OldQuals.removeRestrict();
1187 NewQuals.removeRestrict();
1188 if (OldQuals != NewQuals)
1189 return true;
1190 }
1191
1192 // Though pass_object_size is placed on parameters and takes an argument, we
1193 // consider it to be a function-level modifier for the sake of function
1194 // identity. Either the function has one or more parameters with
1195 // pass_object_size or it doesn't.
1196 if (functionHasPassObjectSizeParams(New) !=
1197 functionHasPassObjectSizeParams(Old))
1198 return true;
1199
1200 // enable_if attributes are an order-sensitive part of the signature.
1201 for (specific_attr_iterator<EnableIfAttr>
1202 NewI = New->specific_attr_begin<EnableIfAttr>(),
1203 NewE = New->specific_attr_end<EnableIfAttr>(),
1204 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1205 OldE = Old->specific_attr_end<EnableIfAttr>();
1206 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1207 if (NewI == NewE || OldI == OldE)
1208 return true;
1209 llvm::FoldingSetNodeID NewID, OldID;
1210 NewI->getCond()->Profile(NewID, Context, true);
1211 OldI->getCond()->Profile(OldID, Context, true);
1212 if (NewID != OldID)
1213 return true;
1214 }
1215
1216 if (getLangOpts().CUDA && ConsiderCudaAttrs) {
1217 // Don't allow overloading of destructors. (In theory we could, but it
1218 // would be a giant change to clang.)
1219 if (isa<CXXDestructorDecl>(New))
1220 return false;
1221
1222 CUDAFunctionTarget NewTarget = IdentifyCUDATarget(New),
1223 OldTarget = IdentifyCUDATarget(Old);
1224 if (NewTarget == CFT_InvalidTarget)
1225 return false;
1226
1227 assert((OldTarget != CFT_InvalidTarget) && "Unexpected invalid target.");
1228
1229 // Allow overloading of functions with same signature and different CUDA
1230 // target attributes.
1231 return NewTarget != OldTarget;
1232 }
1233
1234 // The signatures match; this is not an overload.
1235 return false;
1236}
1237
1238/// Tries a user-defined conversion from From to ToType.
1239///
1240/// Produces an implicit conversion sequence for when a standard conversion
1241/// is not an option. See TryImplicitConversion for more information.
1242static ImplicitConversionSequence
1243TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1244 bool SuppressUserConversions,
1245 bool AllowExplicit,
1246 bool InOverloadResolution,
1247 bool CStyle,
1248 bool AllowObjCWritebackConversion,
1249 bool AllowObjCConversionOnExplicit) {
1250 ImplicitConversionSequence ICS;
1251
1252 if (SuppressUserConversions) {
1253 // We're not in the case above, so there is no conversion that
1254 // we can perform.
1255 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1256 return ICS;
1257 }
1258
1259 // Attempt user-defined conversion.
1260 OverloadCandidateSet Conversions(From->getExprLoc(),
1261 OverloadCandidateSet::CSK_Normal);
1262 switch (IsUserDefinedConversion(S, From, ToType, ICS.UserDefined,
1263 Conversions, AllowExplicit,
1264 AllowObjCConversionOnExplicit)) {
1265 case OR_Success:
1266 case OR_Deleted:
1267 ICS.setUserDefined();
1268 // C++ [over.ics.user]p4:
1269 // A conversion of an expression of class type to the same class
1270 // type is given Exact Match rank, and a conversion of an
1271 // expression of class type to a base class of that type is
1272 // given Conversion rank, in spite of the fact that a copy
1273 // constructor (i.e., a user-defined conversion function) is
1274 // called for those cases.
1275 if (CXXConstructorDecl *Constructor
1276 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1277 QualType FromCanon
1278 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1279 QualType ToCanon
1280 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1281 if (Constructor->isCopyConstructor() &&
1282 (FromCanon == ToCanon ||
1283 S.IsDerivedFrom(From->getBeginLoc(), FromCanon, ToCanon))) {
1284 // Turn this into a "standard" conversion sequence, so that it
1285 // gets ranked with standard conversion sequences.
1286 DeclAccessPair Found = ICS.UserDefined.FoundConversionFunction;
1287 ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
1288 ICS.Standard.setAsIdentityConversion();
1289 ICS.Standard.setFromType(From->getType());
1290 ICS.Standard.setAllToTypes(ToType);
1291 ICS.Standard.CopyConstructor = Constructor;
1292 ICS.Standard.FoundCopyConstructor = Found;
1293 if (ToCanon != FromCanon)
1294 ICS.Standard.Second = ICK_Derived_To_Base;
1295 }
1296 }
1297 break;
1298
1299 case OR_Ambiguous:
1300 ICS.setAmbiguous();
1301 ICS.Ambiguous.setFromType(From->getType());
1302 ICS.Ambiguous.setToType(ToType);
1303 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1304 Cand != Conversions.end(); ++Cand)
1305 if (Cand->Viable)
1306 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
1307 break;
1308
1309 // Fall through.
1310 case OR_No_Viable_Function:
1311 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1312 break;
1313 }
1314
1315 return ICS;
1316}
1317
1318/// TryImplicitConversion - Attempt to perform an implicit conversion
1319/// from the given expression (Expr) to the given type (ToType). This
1320/// function returns an implicit conversion sequence that can be used
1321/// to perform the initialization. Given
1322///
1323/// void f(float f);
1324/// void g(int i) { f(i); }
1325///
1326/// this routine would produce an implicit conversion sequence to
1327/// describe the initialization of f from i, which will be a standard
1328/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1329/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1330//
1331/// Note that this routine only determines how the conversion can be
1332/// performed; it does not actually perform the conversion. As such,
1333/// it will not produce any diagnostics if no conversion is available,
1334/// but will instead return an implicit conversion sequence of kind
1335/// "BadConversion".
1336///
1337/// If @p SuppressUserConversions, then user-defined conversions are
1338/// not permitted.
1339/// If @p AllowExplicit, then explicit user-defined conversions are
1340/// permitted.
1341///
1342/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1343/// writeback conversion, which allows __autoreleasing id* parameters to
1344/// be initialized with __strong id* or __weak id* arguments.
1345static ImplicitConversionSequence
1346TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1347 bool SuppressUserConversions,
1348 bool AllowExplicit,
1349 bool InOverloadResolution,
1350 bool CStyle,
1351 bool AllowObjCWritebackConversion,
1352 bool AllowObjCConversionOnExplicit) {
1353 ImplicitConversionSequence ICS;
1354 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
1355 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
1356 ICS.setStandard(ImplicitConversionSequence::KeepState);
1357 return ICS;
1358 }
1359
1360 if (!S.getLangOpts().CPlusPlus) {
1361 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1362 return ICS;
1363 }
1364
1365 // C++ [over.ics.user]p4:
1366 // A conversion of an expression of class type to the same class
1367 // type is given Exact Match rank, and a conversion of an
1368 // expression of class type to a base class of that type is
1369 // given Conversion rank, in spite of the fact that a copy/move
1370 // constructor (i.e., a user-defined conversion function) is
1371 // called for those cases.
1372 QualType FromType = From->getType();
1373 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
1374 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1375 S.IsDerivedFrom(From->getBeginLoc(), FromType, ToType))) {
1376 ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
1377 ICS.Standard.setAsIdentityConversion();
1378 ICS.Standard.setFromType(FromType);
1379 ICS.Standard.setAllToTypes(ToType);
1380
1381 // We don't actually check at this point whether there is a valid
1382 // copy/move constructor, since overloading just assumes that it
1383 // exists. When we actually perform initialization, we'll find the
1384 // appropriate constructor to copy the returned object, if needed.
1385 ICS.Standard.CopyConstructor = nullptr;
1386
1387 // Determine whether this is considered a derived-to-base conversion.
1388 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
1389 ICS.Standard.Second = ICK_Derived_To_Base;
1390
1391 return ICS;
1392 }
1393
1394 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1395 AllowExplicit, InOverloadResolution, CStyle,
1396 AllowObjCWritebackConversion,
1397 AllowObjCConversionOnExplicit);
1398}
1399
1400ImplicitConversionSequence
1401Sema::TryImplicitConversion(Expr *From, QualType ToType,
1402 bool SuppressUserConversions,
1403 bool AllowExplicit,
1404 bool InOverloadResolution,
1405 bool CStyle,
1406 bool AllowObjCWritebackConversion) {
1407 return ::TryImplicitConversion(*this, From, ToType,
1408 SuppressUserConversions, AllowExplicit,
1409 InOverloadResolution, CStyle,
1410 AllowObjCWritebackConversion,
1411 /*AllowObjCConversionOnExplicit=*/false);
1412}
1413
1414/// PerformImplicitConversion - Perform an implicit conversion of the
1415/// expression From to the type ToType. Returns the
1416/// converted expression. Flavor is the kind of conversion we're
1417/// performing, used in the error message. If @p AllowExplicit,
1418/// explicit user-defined conversions are permitted.
1419ExprResult
1420Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1421 AssignmentAction Action, bool AllowExplicit) {
1422 ImplicitConversionSequence ICS;
1423 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
1424}
1425
1426ExprResult
1427Sema::PerformImplicitConversion(Expr *From, QualType ToType,
1428 AssignmentAction Action, bool AllowExplicit,
1429 ImplicitConversionSequence& ICS) {
1430 if (checkPlaceholderForOverload(*this, From))
1431 return ExprError();
1432
1433 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1434 bool AllowObjCWritebackConversion
1435 = getLangOpts().ObjCAutoRefCount &&
1436 (Action == AA_Passing || Action == AA_Sending);
1437 if (getLangOpts().ObjC)
1438 CheckObjCBridgeRelatedConversions(From->getBeginLoc(), ToType,
1439 From->getType(), From);
1440 ICS = ::TryImplicitConversion(*this, From, ToType,
1441 /*SuppressUserConversions=*/false,
1442 AllowExplicit,
1443 /*InOverloadResolution=*/false,
1444 /*CStyle=*/false,
1445 AllowObjCWritebackConversion,
1446 /*AllowObjCConversionOnExplicit=*/false);
1447 return PerformImplicitConversion(From, ToType, ICS, Action);
1448}
1449
1450/// Determine whether the conversion from FromType to ToType is a valid
1451/// conversion that strips "noexcept" or "noreturn" off the nested function
1452/// type.
1453bool Sema::IsFunctionConversion(QualType FromType, QualType ToType,
1454 QualType &ResultTy) {
1455 if (Context.hasSameUnqualifiedType(FromType, ToType))
1456 return false;
1457
1458 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1459 // or F(t noexcept) -> F(t)
1460 // where F adds one of the following at most once:
1461 // - a pointer
1462 // - a member pointer
1463 // - a block pointer
1464 // Changes here need matching changes in FindCompositePointerType.
1465 CanQualType CanTo = Context.getCanonicalType(ToType);
1466 CanQualType CanFrom = Context.getCanonicalType(FromType);
1467 Type::TypeClass TyClass = CanTo->getTypeClass();
1468 if (TyClass != CanFrom->getTypeClass()) return false;
1469 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1470 if (TyClass == Type::Pointer) {
1471 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1472 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1473 } else if (TyClass == Type::BlockPointer) {
1474 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1475 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1476 } else if (TyClass == Type::MemberPointer) {
1477 auto ToMPT = CanTo.getAs<MemberPointerType>();
1478 auto FromMPT = CanFrom.getAs<MemberPointerType>();
1479 // A function pointer conversion cannot change the class of the function.
1480 if (ToMPT->getClass() != FromMPT->getClass())
1481 return false;
1482 CanTo = ToMPT->getPointeeType();
1483 CanFrom = FromMPT->getPointeeType();
1484 } else {
1485 return false;
1486 }
1487
1488 TyClass = CanTo->getTypeClass();
1489 if (TyClass != CanFrom->getTypeClass()) return false;
1490 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1491 return false;
1492 }
1493
1494 const auto *FromFn = cast<FunctionType>(CanFrom);
1495 FunctionType::ExtInfo FromEInfo = FromFn->getExtInfo();
1496
1497 const auto *ToFn = cast<FunctionType>(CanTo);
1498 FunctionType::ExtInfo ToEInfo = ToFn->getExtInfo();
1499
1500 bool Changed = false;
1501
1502 // Drop 'noreturn' if not present in target type.
1503 if (FromEInfo.getNoReturn() && !ToEInfo.getNoReturn()) {
1504 FromFn = Context.adjustFunctionType(FromFn, FromEInfo.withNoReturn(false));
1505 Changed = true;
1506 }
1507
1508 // Drop 'noexcept' if not present in target type.
1509 if (const auto *FromFPT = dyn_cast<FunctionProtoType>(FromFn)) {
1510 const auto *ToFPT = cast<FunctionProtoType>(ToFn);
1511 if (FromFPT->isNothrow() && !ToFPT->isNothrow()) {
1512 FromFn = cast<FunctionType>(
1513 Context.getFunctionTypeWithExceptionSpec(QualType(FromFPT, 0),
1514 EST_None)
1515 .getTypePtr());
1516 Changed = true;
1517 }
1518
1519 // Convert FromFPT's ExtParameterInfo if necessary. The conversion is valid
1520 // only if the ExtParameterInfo lists of the two function prototypes can be
1521 // merged and the merged list is identical to ToFPT's ExtParameterInfo list.
1522 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
1523 bool CanUseToFPT, CanUseFromFPT;
1524 if (Context.mergeExtParameterInfo(ToFPT, FromFPT, CanUseToFPT,
1525 CanUseFromFPT, NewParamInfos) &&
1526 CanUseToFPT && !CanUseFromFPT) {
1527 FunctionProtoType::ExtProtoInfo ExtInfo = FromFPT->getExtProtoInfo();
1528 ExtInfo.ExtParameterInfos =
1529 NewParamInfos.empty() ? nullptr : NewParamInfos.data();
1530 QualType QT = Context.getFunctionType(FromFPT->getReturnType(),
1531 FromFPT->getParamTypes(), ExtInfo);
1532 FromFn = QT->getAs<FunctionType>();
1533 Changed = true;
1534 }
1535 }
1536
1537 if (!Changed)
1538 return false;
1539
1540 assert(QualType(FromFn, 0).isCanonical());
1541 if (QualType(FromFn, 0) != CanTo) return false;
1542
1543 ResultTy = ToType;
1544 return true;
1545}
1546
1547/// Determine whether the conversion from FromType to ToType is a valid
1548/// vector conversion.
1549///
1550/// \param ICK Will be set to the vector conversion kind, if this is a vector
1551/// conversion.
1552static bool IsVectorConversion(Sema &S, QualType FromType,
1553 QualType ToType, ImplicitConversionKind &ICK) {
1554 // We need at least one of these types to be a vector type to have a vector
1555 // conversion.
1556 if (!ToType->isVectorType() && !FromType->isVectorType())
1557 return false;
1558
1559 // Identical types require no conversions.
1560 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
1561 return false;
1562
1563 // There are no conversions between extended vector types, only identity.
1564 if (ToType->isExtVectorType()) {
1565 // There are no conversions between extended vector types other than the
1566 // identity conversion.
1567 if (FromType->isExtVectorType())
1568 return false;
1569
1570 // Vector splat from any arithmetic type to a vector.
1571 if (FromType->isArithmeticType()) {
1572 ICK = ICK_Vector_Splat;
1573 return true;
1574 }
1575 }
1576
1577 // We can perform the conversion between vector types in the following cases:
1578 // 1)vector types are equivalent AltiVec and GCC vector types
1579 // 2)lax vector conversions are permitted and the vector types are of the
1580 // same size
1581 if (ToType->isVectorType() && FromType->isVectorType()) {
1582 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1583 S.isLaxVectorConversion(FromType, ToType)) {
1584 ICK = ICK_Vector_Conversion;
1585 return true;
1586 }
1587 }
1588
1589 return false;
1590}
1591
1592static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1593 bool InOverloadResolution,
1594 StandardConversionSequence &SCS,
1595 bool CStyle);
1596
1597/// IsStandardConversion - Determines whether there is a standard
1598/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1599/// expression From to the type ToType. Standard conversion sequences
1600/// only consider non-class types; for conversions that involve class
1601/// types, use TryImplicitConversion. If a conversion exists, SCS will
1602/// contain the standard conversion sequence required to perform this
1603/// conversion and this routine will return true. Otherwise, this
1604/// routine will return false and the value of SCS is unspecified.
1605static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1606 bool InOverloadResolution,
1607 StandardConversionSequence &SCS,
1608 bool CStyle,
1609 bool AllowObjCWritebackConversion) {
1610 QualType FromType = From->getType();
1611
1612 // Standard conversions (C++ [conv])
1613 SCS.setAsIdentityConversion();
1614 SCS.IncompatibleObjC = false;
1615 SCS.setFromType(FromType);
1616 SCS.CopyConstructor = nullptr;
1617
1618 // There are no standard conversions for class types in C++, so
1619 // abort early. When overloading in C, however, we do permit them.
1620 if (S.getLangOpts().CPlusPlus &&
1621 (FromType->isRecordType() || ToType->isRecordType()))
1622 return false;
1623
1624 // The first conversion can be an lvalue-to-rvalue conversion,
1625 // array-to-pointer conversion, or function-to-pointer conversion
1626 // (C++ 4p1).
1627
1628 if (FromType == S.Context.OverloadTy) {
1629 DeclAccessPair AccessPair;
1630 if (FunctionDecl *Fn
1631 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1632 AccessPair)) {
1633 // We were able to resolve the address of the overloaded function,
1634 // so we can convert to the type of that function.
1635 FromType = Fn->getType();
1636 SCS.setFromType(FromType);
1637
1638 // we can sometimes resolve &foo<int> regardless of ToType, so check
1639 // if the type matches (identity) or we are converting to bool
1640 if (!S.Context.hasSameUnqualifiedType(
1641 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1642 QualType resultTy;
1643 // if the function type matches except for [[noreturn]], it's ok
1644 if (!S.IsFunctionConversion(FromType,
1645 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1646 // otherwise, only a boolean conversion is standard
1647 if (!ToType->isBooleanType())
1648 return false;
1649 }
1650
1651 // Check if the "from" expression is taking the address of an overloaded
1652 // function and recompute the FromType accordingly. Take advantage of the
1653 // fact that non-static member functions *must* have such an address-of
1654 // expression.
1655 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1656 if (Method && !Method->isStatic()) {
1657 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1658 "Non-unary operator on non-static member address");
1659 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1660 == UO_AddrOf &&
1661 "Non-address-of operator on non-static member address");
1662 const Type *ClassType
1663 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1664 FromType = S.Context.getMemberPointerType(FromType, ClassType);
1665 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1666 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1667 UO_AddrOf &&
1668 "Non-address-of operator for overloaded function expression");
1669 FromType = S.Context.getPointerType(FromType);
1670 }
1671
1672 // Check that we've computed the proper type after overload resolution.
1673 // FIXME: FixOverloadedFunctionReference has side-effects; we shouldn't
1674 // be calling it from within an NDEBUG block.
1675 assert(S.Context.hasSameType(
1676 FromType,
1677 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
1678 } else {
1679 return false;
1680 }
1681 }
1682 // Lvalue-to-rvalue conversion (C++11 4.1):
1683 // A glvalue (3.10) of a non-function, non-array type T can
1684 // be converted to a prvalue.
1685 bool argIsLValue = From->isGLValue();
1686 if (argIsLValue &&
1687 !FromType->isFunctionType() && !FromType->isArrayType() &&
1688 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
1689 SCS.First = ICK_Lvalue_To_Rvalue;
1690
1691 // C11 6.3.2.1p2:
1692 // ... if the lvalue has atomic type, the value has the non-atomic version
1693 // of the type of the lvalue ...
1694 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1695 FromType = Atomic->getValueType();
1696
1697 // If T is a non-class type, the type of the rvalue is the
1698 // cv-unqualified version of T. Otherwise, the type of the rvalue
1699 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1700 // just strip the qualifiers because they don't matter.
1701 FromType = FromType.getUnqualifiedType();
1702 } else if (FromType->isArrayType()) {
1703 // Array-to-pointer conversion (C++ 4.2)
1704 SCS.First = ICK_Array_To_Pointer;
1705
1706 // An lvalue or rvalue of type "array of N T" or "array of unknown
1707 // bound of T" can be converted to an rvalue of type "pointer to
1708 // T" (C++ 4.2p1).
1709 FromType = S.Context.getArrayDecayedType(FromType);
1710
1711 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
1712 // This conversion is deprecated in C++03 (D.4)
1713 SCS.DeprecatedStringLiteralToCharPtr = true;
1714
1715 // For the purpose of ranking in overload resolution
1716 // (13.3.3.1.1), this conversion is considered an
1717 // array-to-pointer conversion followed by a qualification
1718 // conversion (4.4). (C++ 4.2p2)
1719 SCS.Second = ICK_Identity;
1720 SCS.Third = ICK_Qualification;
1721 SCS.QualificationIncludesObjCLifetime = false;
1722 SCS.setAllToTypes(FromType);
1723 return true;
1724 }
1725 } else if (FromType->isFunctionType() && argIsLValue) {
1726 // Function-to-pointer conversion (C++ 4.3).
1727 SCS.First = ICK_Function_To_Pointer;
1728
1729 if (auto *DRE = dyn_cast<DeclRefExpr>(From->IgnoreParenCasts()))
1730 if (auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl()))
1731 if (!S.checkAddressOfFunctionIsAvailable(FD))
1732 return false;
1733
1734 // An lvalue of function type T can be converted to an rvalue of
1735 // type "pointer to T." The result is a pointer to the
1736 // function. (C++ 4.3p1).
1737 FromType = S.Context.getPointerType(FromType);
1738 } else {
1739 // We don't require any conversions for the first step.
1740 SCS.First = ICK_Identity;
1741 }
1742 SCS.setToType(0, FromType);
1743
1744 // The second conversion can be an integral promotion, floating
1745 // point promotion, integral conversion, floating point conversion,
1746 // floating-integral conversion, pointer conversion,
1747 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
1748 // For overloading in C, this can also be a "compatible-type"
1749 // conversion.
1750 bool IncompatibleObjC = false;
1751 ImplicitConversionKind SecondICK = ICK_Identity;
1752 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
1753 // The unqualified versions of the types are the same: there's no
1754 // conversion to do.
1755 SCS.Second = ICK_Identity;
1756 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
1757 // Integral promotion (C++ 4.5).
1758 SCS.Second = ICK_Integral_Promotion;
1759 FromType = ToType.getUnqualifiedType();
1760 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
1761 // Floating point promotion (C++ 4.6).
1762 SCS.Second = ICK_Floating_Promotion;
1763 FromType = ToType.getUnqualifiedType();
1764 } else if (S.IsComplexPromotion(FromType, ToType)) {
1765 // Complex promotion (Clang extension)
1766 SCS.Second = ICK_Complex_Promotion;
1767 FromType = ToType.getUnqualifiedType();
1768 } else if (ToType->isBooleanType() &&
1769 (FromType->isArithmeticType() ||
1770 FromType->isAnyPointerType() ||
1771 FromType->isBlockPointerType() ||
1772 FromType->isMemberPointerType() ||
1773 FromType->isNullPtrType())) {
1774 // Boolean conversions (C++ 4.12).
1775 SCS.Second = ICK_Boolean_Conversion;
1776 FromType = S.Context.BoolTy;
1777 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
1778 ToType->isIntegralType(S.Context)) {
1779 // Integral conversions (C++ 4.7).
1780 SCS.Second = ICK_Integral_Conversion;
1781 FromType = ToType.getUnqualifiedType();
1782 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
1783 // Complex conversions (C99 6.3.1.6)
1784 SCS.Second = ICK_Complex_Conversion;
1785 FromType = ToType.getUnqualifiedType();
1786 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1787 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
1788 // Complex-real conversions (C99 6.3.1.7)
1789 SCS.Second = ICK_Complex_Real;
1790 FromType = ToType.getUnqualifiedType();
1791 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
1792 // FIXME: disable conversions between long double and __float128 if
1793 // their representation is different until there is back end support
1794 // We of course allow this conversion if long double is really double.
1795 if (&S.Context.getFloatTypeSemantics(FromType) !=
1796 &S.Context.getFloatTypeSemantics(ToType)) {
1797 bool Float128AndLongDouble = ((FromType == S.Context.Float128Ty &&
1798 ToType == S.Context.LongDoubleTy) ||
1799 (FromType == S.Context.LongDoubleTy &&
1800 ToType == S.Context.Float128Ty));
1801 if (Float128AndLongDouble &&
1802 (&S.Context.getFloatTypeSemantics(S.Context.LongDoubleTy) ==
1803 &llvm::APFloat::PPCDoubleDouble()))
1804 return false;
1805 }
1806 // Floating point conversions (C++ 4.8).
1807 SCS.Second = ICK_Floating_Conversion;
1808 FromType = ToType.getUnqualifiedType();
1809 } else if ((FromType->isRealFloatingType() &&
1810 ToType->isIntegralType(S.Context)) ||
1811 (FromType->isIntegralOrUnscopedEnumerationType() &&
1812 ToType->isRealFloatingType())) {
1813 // Floating-integral conversions (C++ 4.9).
1814 SCS.Second = ICK_Floating_Integral;
1815 FromType = ToType.getUnqualifiedType();
1816 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1817 SCS.Second = ICK_Block_Pointer_Conversion;
1818 } else if (AllowObjCWritebackConversion &&
1819 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1820 SCS.Second = ICK_Writeback_Conversion;
1821 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1822 FromType, IncompatibleObjC)) {
1823 // Pointer conversions (C++ 4.10).
1824 SCS.Second = ICK_Pointer_Conversion;
1825 SCS.IncompatibleObjC = IncompatibleObjC;
1826 FromType = FromType.getUnqualifiedType();
1827 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1828 InOverloadResolution, FromType)) {
1829 // Pointer to member conversions (4.11).
1830 SCS.Second = ICK_Pointer_Member;
1831 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
1832 SCS.Second = SecondICK;
1833 FromType = ToType.getUnqualifiedType();
1834 } else if (!S.getLangOpts().CPlusPlus &&
1835 S.Context.typesAreCompatible(ToType, FromType)) {
1836 // Compatible conversions (Clang extension for C function overloading)
1837 SCS.Second = ICK_Compatible_Conversion;
1838 FromType = ToType.getUnqualifiedType();
1839 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1840 InOverloadResolution,
1841 SCS, CStyle)) {
1842 SCS.Second = ICK_TransparentUnionConversion;
1843 FromType = ToType;
1844 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1845 CStyle)) {
1846 // tryAtomicConversion has updated the standard conversion sequence
1847 // appropriately.
1848 return true;
1849 } else if (ToType->isEventT() &&
1850 From->isIntegerConstantExpr(S.getASTContext()) &&
1851 From->EvaluateKnownConstInt(S.getASTContext()) == 0) {
1852 SCS.Second = ICK_Zero_Event_Conversion;
1853 FromType = ToType;
1854 } else if (ToType->isQueueT() &&
1855 From->isIntegerConstantExpr(S.getASTContext()) &&
1856 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1857 SCS.Second = ICK_Zero_Queue_Conversion;
1858 FromType = ToType;
1859 } else {
1860 // No second conversion required.
1861 SCS.Second = ICK_Identity;
1862 }
1863 SCS.setToType(1, FromType);
1864
1865 // The third conversion can be a function pointer conversion or a
1866 // qualification conversion (C++ [conv.fctptr], [conv.qual]).
1867 bool ObjCLifetimeConversion;
1868 if (S.IsFunctionConversion(FromType, ToType, FromType)) {
1869 // Function pointer conversions (removing 'noexcept') including removal of
1870 // 'noreturn' (Clang extension).
1871 SCS.Third = ICK_Function_Conversion;
1872 } else if (S.IsQualificationConversion(FromType, ToType, CStyle,
1873 ObjCLifetimeConversion)) {
1874 SCS.Third = ICK_Qualification;
1875 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
1876 // Check for CHERI type conversion
1877 if (FromType->isCHERICapabilityType(S.getASTContext())
1878 != ToType->isCHERICapabilityType(S.getASTContext())) {
1879 // Check implicit pointer-to-capability conversion.
1880 // Don't output warnings at this point as they will be output later.
1881 bool validCHERIConversion = false;
1882 if (FromType->isPointerType() && ToType->isPointerType() && ToType->getAs<PointerType>()->isCHERICapability())
1883 validCHERIConversion = S.ImpCastPointerToCHERICapability(FromType, ToType, From, false);
1884
1885 SCS.setInvalidCHERIConversion(!validCHERIConversion);
1886 }
1887 FromType = ToType;
1888 } else {
1889 // No conversion required
1890 SCS.Third = ICK_Identity;
1891 }
1892
1893 // C++ [over.best.ics]p6:
1894 // [...] Any difference in top-level cv-qualification is
1895 // subsumed by the initialization itself and does not constitute
1896 // a conversion. [...]
1897 QualType CanonFrom = S.Context.getCanonicalType(FromType);
1898 QualType CanonTo = S.Context.getCanonicalType(ToType);
1899 if (CanonFrom.getLocalUnqualifiedType()
1900 == CanonTo.getLocalUnqualifiedType() &&
1901 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
1902 FromType = ToType;
1903 CanonFrom = CanonTo;
1904 }
1905
1906 SCS.setToType(2, FromType);
1907
1908 if (CanonFrom == CanonTo)
1909 return true;
1910
1911 // If we have not converted the argument type to the parameter type,
1912 // this is a bad conversion sequence, unless we're resolving an overload in C.
1913 if (S.getLangOpts().CPlusPlus || !InOverloadResolution)
1914 return false;
1915
1916 ExprResult ER = ExprResult{From};
1917 Sema::AssignConvertType Conv =
1918 S.CheckSingleAssignmentConstraints(ToType, ER,
1919 /*Diagnose=*/false,
1920 /*DiagnoseCFAudited=*/false,
1921 /*ConvertRHS=*/false);
1922 ImplicitConversionKind SecondConv;
1923 switch (Conv) {
1924 case Sema::Compatible:
1925 SecondConv = ICK_C_Only_Conversion;
1926 break;
1927 // For our purposes, discarding qualifiers is just as bad as using an
1928 // incompatible pointer. Note that an IncompatiblePointer conversion can drop
1929 // qualifiers, as well.
1930 case Sema::CompatiblePointerDiscardsQualifiers:
1931 case Sema::IncompatiblePointer:
1932 case Sema::IncompatiblePointerSign:
1933 SecondConv = ICK_Incompatible_Pointer_Conversion;
1934 break;
1935 default:
1936 return false;
1937 }
1938
1939 // First can only be an lvalue conversion, so we pretend that this was the
1940 // second conversion. First should already be valid from earlier in the
1941 // function.
1942 SCS.Second = SecondConv;
1943 SCS.setToType(1, ToType);
1944
1945 // Third is Identity, because Second should rank us worse than any other
1946 // conversion. This could also be ICK_Qualification, but it's simpler to just
1947 // lump everything in with the second conversion, and we don't gain anything
1948 // from making this ICK_Qualification.
1949 SCS.Third = ICK_Identity;
1950 SCS.setToType(2, ToType);
1951 return true;
1952}
1953
1954static bool
1955IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1956 QualType &ToType,
1957 bool InOverloadResolution,
1958 StandardConversionSequence &SCS,
1959 bool CStyle) {
1960
1961 const RecordType *UT = ToType->getAsUnionType();
1962 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1963 return false;
1964 // The field to initialize within the transparent union.
1965 RecordDecl *UD = UT->getDecl();
1966 // It's compatible if the expression matches any of the fields.
1967 for (const auto *it : UD->fields()) {
1968 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1969 CStyle, /*ObjCWritebackConversion=*/false)) {
1970 ToType = it->getType();
1971 return true;
1972 }
1973 }
1974 return false;
1975}
1976
1977/// IsIntegralPromotion - Determines whether the conversion from the
1978/// expression From (whose potentially-adjusted type is FromType) to
1979/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1980/// sets PromotedType to the promoted type.
1981bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
1982 const BuiltinType *To = ToType->getAs<BuiltinType>();
1983 // All integers are built-in.
1984 if (!To) {
1985 return false;
1986 }
1987
1988 // An rvalue of type char, signed char, unsigned char, short int, or
1989 // unsigned short int can be converted to an rvalue of type int if
1990 // int can represent all the values of the source type; otherwise,
1991 // the source rvalue can be converted to an rvalue of type unsigned
1992 // int (C++ 4.5p1).
1993 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1994 !FromType->isEnumeralType()) {
1995 if (// We can promote any signed, promotable integer type to an int
1996 (FromType->isSignedIntegerType() ||
1997 // We can promote any unsigned integer type whose size is
1998 // less than int to an int.
1999 Context.getTypeSize(FromType) < Context.getTypeSize(ToType))) {
2000 return To->getKind() == BuiltinType::Int;
2001 }
2002
2003 return To->getKind() == BuiltinType::UInt;
2004 }
2005
2006 // C++11 [conv.prom]p3:
2007 // A prvalue of an unscoped enumeration type whose underlying type is not
2008 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
2009 // following types that can represent all the values of the enumeration
2010 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
2011 // unsigned int, long int, unsigned long int, long long int, or unsigned
2012 // long long int. If none of the types in that list can represent all the
2013 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
2014 // type can be converted to an rvalue a prvalue of the extended integer type
2015 // with lowest integer conversion rank (4.13) greater than the rank of long
2016 // long in which all the values of the enumeration can be represented. If
2017 // there are two such extended types, the signed one is chosen.
2018 // C++11 [conv.prom]p4:
2019 // A prvalue of an unscoped enumeration type whose underlying type is fixed
2020 // can be converted to a prvalue of its underlying type. Moreover, if
2021 // integral promotion can be applied to its underlying type, a prvalue of an
2022 // unscoped enumeration type whose underlying type is fixed can also be
2023 // converted to a prvalue of the promoted underlying type.
2024 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
2025 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
2026 // provided for a scoped enumeration.
2027 if (FromEnumType->getDecl()->isScoped())
2028 return false;
2029
2030 // We can perform an integral promotion to the underlying type of the enum,
2031 // even if that's not the promoted type. Note that the check for promoting
2032 // the underlying type is based on the type alone, and does not consider
2033 // the bitfield-ness of the actual source expression.
2034 if (FromEnumType->getDecl()->isFixed()) {
2035 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
2036 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
2037 IsIntegralPromotion(nullptr, Underlying, ToType);
2038 }
2039
2040 // We have already pre-calculated the promotion type, so this is trivial.
2041 if (ToType->isIntegerType() &&
2042 isCompleteType(From->getBeginLoc(), FromType))
2043 return Context.hasSameUnqualifiedType(
2044 ToType, FromEnumType->getDecl()->getPromotionType());
2045
2046 // C++ [conv.prom]p5:
2047 // If the bit-field has an enumerated type, it is treated as any other
2048 // value of that type for promotion purposes.
2049 //
2050 // ... so do not fall through into the bit-field checks below in C++.
2051 if (getLangOpts().CPlusPlus)
2052 return false;
2053 }
2054
2055 // C++0x [conv.prom]p2:
2056 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
2057 // to an rvalue a prvalue of the first of the following types that can
2058 // represent all the values of its underlying type: int, unsigned int,
2059 // long int, unsigned long int, long long int, or unsigned long long int.
2060 // If none of the types in that list can represent all the values of its
2061 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
2062 // or wchar_t can be converted to an rvalue a prvalue of its underlying
2063 // type.
2064 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
2065 ToType->isIntegerType()) {
2066 // Determine whether the type we're converting from is signed or
2067 // unsigned.
2068 bool FromIsSigned = FromType->isSignedIntegerType();
2069 uint64_t FromSize = Context.getTypeSize(FromType);
2070
2071 // The types we'll try to promote to, in the appropriate
2072 // order. Try each of these types.
2073 QualType PromoteTypes[6] = {
2074 Context.IntTy, Context.UnsignedIntTy,
2075 Context.LongTy, Context.UnsignedLongTy ,
2076 Context.LongLongTy, Context.UnsignedLongLongTy
2077 };
2078 for (int Idx = 0; Idx < 6; ++Idx) {
2079 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
2080 if (FromSize < ToSize ||
2081 (FromSize == ToSize &&
2082 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
2083 // We found the type that we can promote to. If this is the
2084 // type we wanted, we have a promotion. Otherwise, no
2085 // promotion.
2086 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
2087 }
2088 }
2089 }
2090
2091 // An rvalue for an integral bit-field (9.6) can be converted to an
2092 // rvalue of type int if int can represent all the values of the
2093 // bit-field; otherwise, it can be converted to unsigned int if
2094 // unsigned int can represent all the values of the bit-field. If
2095 // the bit-field is larger yet, no integral promotion applies to
2096 // it. If the bit-field has an enumerated type, it is treated as any
2097 // other value of that type for promotion purposes (C++ 4.5p3).
2098 // FIXME: We should delay checking of bit-fields until we actually perform the
2099 // conversion.
2100 //
2101 // FIXME: In C, only bit-fields of types _Bool, int, or unsigned int may be
2102 // promoted, per C11 6.3.1.1/2. We promote all bit-fields (including enum
2103 // bit-fields and those whose underlying type is larger than int) for GCC
2104 // compatibility.
2105 if (From) {
2106 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
2107 llvm::APSInt BitWidth;
2108 if (FromType->isIntegralType(Context) &&
2109 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
2110 llvm::APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
2111 ToSize = Context.getTypeSize(ToType);
2112
2113 // Are we promoting to an int from a bitfield that fits in an int?
2114 if (BitWidth < ToSize ||
2115 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
2116 return To->getKind() == BuiltinType::Int;
2117 }
2118
2119 // Are we promoting to an unsigned int from an unsigned bitfield
2120 // that fits into an unsigned int?
2121 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
2122 return To->getKind() == BuiltinType::UInt;
2123 }
2124
2125 return false;
2126 }
2127 }
2128 }
2129
2130 // An rvalue of type bool can be converted to an rvalue of type int,
2131 // with false becoming zero and true becoming one (C++ 4.5p4).
2132 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
2133 return true;
2134 }
2135
2136 return false;
2137}
2138
2139/// IsFloatingPointPromotion - Determines whether the conversion from
2140/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
2141/// returns true and sets PromotedType to the promoted type.
2142bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
2143 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
2144 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
2145 /// An rvalue of type float can be converted to an rvalue of type
2146 /// double. (C++ 4.6p1).
2147 if (FromBuiltin->getKind() == BuiltinType::Float &&
2148 ToBuiltin->getKind() == BuiltinType::Double)
2149 return true;
2150
2151 // C99 6.3.1.5p1:
2152 // When a float is promoted to double or long double, or a
2153 // double is promoted to long double [...].
2154 if (!getLangOpts().CPlusPlus &&
2155 (FromBuiltin->getKind() == BuiltinType::Float ||
2156 FromBuiltin->getKind() == BuiltinType::Double) &&
2157 (ToBuiltin->getKind() == BuiltinType::LongDouble ||
2158 ToBuiltin->getKind() == BuiltinType::Float128))
2159 return true;
2160
2161 // Half can be promoted to float.
2162 if (!getLangOpts().NativeHalfType &&
2163 FromBuiltin->getKind() == BuiltinType::Half &&
2164 ToBuiltin->getKind() == BuiltinType::Float)
2165 return true;
2166 }
2167
2168 return false;
2169}
2170
2171/// Determine if a conversion is a complex promotion.
2172///
2173/// A complex promotion is defined as a complex -> complex conversion
2174/// where the conversion between the underlying real types is a
2175/// floating-point or integral promotion.
2176bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
2177 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
2178 if (!FromComplex)
2179 return false;
2180
2181 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
2182 if (!ToComplex)
2183 return false;
2184
2185 return IsFloatingPointPromotion(FromComplex->getElementType(),
2186 ToComplex->getElementType()) ||
2187 IsIntegralPromotion(nullptr, FromComplex->getElementType(),
2188 ToComplex->getElementType());
2189}
2190
2191/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
2192/// the pointer type FromPtr to a pointer to type ToPointee, with the
2193/// same type qualifiers as FromPtr has on its pointee type. ToType,
2194/// if non-empty, will be a pointer to ToType that may or may not have
2195/// the right set of qualifiers on its pointee.
2196///
2197static QualType
2198BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
2199 QualType ToPointee, QualType ToType,
2200 ASTContext &Context,
2201 bool StripObjCLifetime = false) {
2202 assert((FromPtr->getTypeClass() == Type::Pointer ||
2203 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
2204 "Invalid similarly-qualified pointer type");
2205
2206 /// Conversions to 'id' subsume cv-qualifier conversions.
2207 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
2208 return ToType.getUnqualifiedType();
2209
2210 const bool FromIsCap = FromPtr->isCHERICapabilityType(Context);
2211 ASTContext::PointerInterpretationKind PIK =
2212 FromIsCap ? ASTContext::PIK_Capability : ASTContext::PIK_Integer;
2213 QualType CanonFromPointee
2214 = Context.getCanonicalType(FromPtr->getPointeeType());
2215 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
2216 Qualifiers Quals = CanonFromPointee.getQualifiers();
2217
2218 if (StripObjCLifetime)
2219 Quals.removeObjCLifetime();
2220
2221 // Exact qualifier match -> return the pointer type we're converting to.
2222 if (CanonToPointee.getLocalQualifiers() == Quals) {
2223 // ToType is exactly what we need. Return it.
2224 // XXXAR: but only if the memory capability qualifier matches
2225 if (ToType->isCHERICapabilityType(Context) == FromIsCap && !ToType.isNull())
2226 return ToType.getUnqualifiedType();
2227
2228 // Build a pointer to ToPointee. It has the right qualifiers
2229 // already.
2230 if (isa<ObjCObjectPointerType>(ToType))
2231 return Context.getObjCObjectPointerType(ToPointee);
2232 return Context.getPointerType(ToPointee, PIK);
2233 }
2234
2235 // Just build a canonical type that has the right qualifiers.
2236 QualType QualifiedCanonToPointee
2237 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
2238
2239 if (isa<ObjCObjectPointerType>(ToType))
2240 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
2241 return Context.getPointerType(QualifiedCanonToPointee, PIK);
2242}
2243
2244static bool isNullPointerConstantForConversion(Expr *Expr,
2245 bool InOverloadResolution,
2246 ASTContext &Context) {
2247 // Handle value-dependent integral null pointer constants correctly.
2248 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
2249 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
2250 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
2251 return !InOverloadResolution;
2252
2253 return Expr->isNullPointerConstant(Context,
2254 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2255 : Expr::NPC_ValueDependentIsNull);
2256}
2257
2258/// IsPointerConversion - Determines whether the conversion of the
2259/// expression From, which has the (possibly adjusted) type FromType,
2260/// can be converted to the type ToType via a pointer conversion (C++
2261/// 4.10). If so, returns true and places the converted type (that
2262/// might differ from ToType in its cv-qualifiers at some level) into
2263/// ConvertedType.
2264///
2265/// This routine also supports conversions to and from block pointers
2266/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2267/// pointers to interfaces. FIXME: Once we've determined the
2268/// appropriate overloading rules for Objective-C, we may want to
2269/// split the Objective-C checks into a different routine; however,
2270/// GCC seems to consider all of these conversions to be pointer
2271/// conversions, so for now they live here. IncompatibleObjC will be
2272/// set if the conversion is an allowed Objective-C conversion that
2273/// should result in a warning.
2274bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
2275 bool InOverloadResolution,
2276 QualType& ConvertedType,
2277 bool &IncompatibleObjC) {
2278 IncompatibleObjC = false;
2279 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2280 IncompatibleObjC))
2281 return true;
2282
2283 // Conversion from a null pointer constant to any Objective-C pointer type.
2284 if (ToType->isObjCObjectPointerType() &&
2285 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2286 ConvertedType = ToType;
2287 return true;
2288 }
2289
2290 // Blocks: Block pointers can be converted to void*.
2291 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
2292 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
2293 ConvertedType = ToType;
2294 return true;
2295 }
2296 // Blocks: A null pointer constant can be converted to a block
2297 // pointer type.
2298 if (ToType->isBlockPointerType() &&
2299 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2300 ConvertedType = ToType;
2301 return true;
2302 }
2303
2304 // If the left-hand-side is nullptr_t, the right side can be a null
2305 // pointer constant.
2306 if (ToType->isNullPtrType() &&
2307 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2308 ConvertedType = ToType;
2309 return true;
2310 }
2311
2312 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
2313 if (!ToTypePtr)
2314 return false;
2315
2316 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
2317 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
2318 ConvertedType = ToType;
2319 return true;
2320 }
2321
2322 // Beyond this point, both types need to be pointers
2323 // , including objective-c pointers.
2324 QualType ToPointeeType = ToTypePtr->getPointeeType();
2325 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
2326 !getLangOpts().ObjCAutoRefCount) {
2327 ConvertedType = BuildSimilarlyQualifiedPointerType(
2328 FromType->getAs<ObjCObjectPointerType>(),
2329 ToPointeeType,
2330 ToType, Context);
2331 return true;
2332 }
2333 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
2334 if (!FromTypePtr)
2335 return false;
2336
2337 QualType FromPointeeType = FromTypePtr->getPointeeType();
2338
2339 // If the unqualified pointee types are the same, this can't be a
2340 // pointer conversion, so don't do all of the work below.
2341 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2342 return false;
2343
2344 // An rvalue of type "pointer to cv T," where T is an object type,
2345 // can be converted to an rvalue of type "pointer to cv void" (C++
2346 // 4.10p2).
2347 if (FromPointeeType->isIncompleteOrObjectType() &&
2348 ToPointeeType->isVoidType()) {
2349 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2350 ToPointeeType,
2351 ToType, Context,
2352 /*StripObjCLifetime=*/true);
2353 assert(FromType->isCHERICapabilityType(Context) ==
2354 ConvertedType->isCHERICapabilityType(Context) &&
2355 "Converted type should retain capability/pointer");
2356 return true;
2357 }
2358
2359 // MSVC allows implicit function to void* type conversion.
2360 if (getLangOpts().MSVCCompat && FromPointeeType->isFunctionType() &&
2361 ToPointeeType->isVoidType()) {
2362 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2363 ToPointeeType,
2364 ToType, Context);
2365 return true;
2366 }
2367
2368 // When we're overloading in C, we allow a special kind of pointer
2369 // conversion for compatible-but-not-identical pointee types.
2370 if (!getLangOpts().CPlusPlus &&
2371 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
2372 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2373 ToPointeeType,
2374 ToType, Context);
2375 return true;
2376 }
2377
2378 // C++ [conv.ptr]p3:
2379 //
2380 // An rvalue of type "pointer to cv D," where D is a class type,
2381 // can be converted to an rvalue of type "pointer to cv B," where
2382 // B is a base class (clause 10) of D. If B is an inaccessible
2383 // (clause 11) or ambiguous (10.2) base class of D, a program that
2384 // necessitates this conversion is ill-formed. The result of the
2385 // conversion is a pointer to the base class sub-object of the
2386 // derived class object. The null pointer value is converted to
2387 // the null pointer value of the destination type.
2388 //
2389 // Note that we do not check for ambiguity or inaccessibility
2390 // here. That is handled by CheckPointerConversion.
2391 if (getLangOpts().CPlusPlus && FromPointeeType->isRecordType() &&
2392 ToPointeeType->isRecordType() &&
2393 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
2394 IsDerivedFrom(From->getBeginLoc(), FromPointeeType, ToPointeeType)) {
2395 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2396 ToPointeeType,
2397 ToType, Context);
2398 return true;
2399 }
2400
2401 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2402 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2403 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2404 ToPointeeType,
2405 ToType, Context);
2406 return true;
2407 }
2408
2409 return false;
2410}
2411
2412/// Adopt the given qualifiers for the given type.
2413static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2414 Qualifiers TQs = T.getQualifiers();
2415
2416 // Check whether qualifiers already match.
2417 if (TQs == Qs)
2418 return T;
2419
2420 if (Qs.compatiblyIncludes(TQs))
2421 return Context.getQualifiedType(T, Qs);
2422
2423 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2424}
2425
2426/// isObjCPointerConversion - Determines whether this is an
2427/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2428/// with the same arguments and return values.
2429bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
2430 QualType& ConvertedType,
2431 bool &IncompatibleObjC) {
2432 if (!getLangOpts().ObjC)
2433 return false;
2434
2435 // The set of qualifiers on the type we're converting from.
2436 Qualifiers FromQualifiers = FromType.getQualifiers();
2437
2438 // First, we handle all conversions on ObjC object pointer types.
2439 const ObjCObjectPointerType* ToObjCPtr =
2440 ToType->getAs<ObjCObjectPointerType>();
2441 const ObjCObjectPointerType *FromObjCPtr =
2442 FromType->getAs<ObjCObjectPointerType>();
2443
2444 if (ToObjCPtr && FromObjCPtr) {
2445 // If the pointee types are the same (ignoring qualifications),
2446 // then this is not a pointer conversion.
2447 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2448 FromObjCPtr->getPointeeType()))
2449 return false;
2450
2451 // Conversion between Objective-C pointers.
2452 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
2453 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2454 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
2455 if (getLangOpts().CPlusPlus && LHS && RHS &&
2456 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2457 FromObjCPtr->getPointeeType()))
2458 return false;
2459 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2460 ToObjCPtr->getPointeeType(),
2461 ToType, Context);
2462 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2463 return true;
2464 }
2465
2466 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2467 // Okay: this is some kind of implicit downcast of Objective-C
2468 // interfaces, which is permitted. However, we're going to
2469 // complain about it.
2470 IncompatibleObjC = true;
2471 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
2472 ToObjCPtr->getPointeeType(),
2473 ToType, Context);
2474 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2475 return true;
2476 }
2477 }
2478 // Beyond this point, both types need to be C pointers or block pointers.
2479 QualType ToPointeeType;
2480 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
2481 ToPointeeType = ToCPtr->getPointeeType();
2482 else if (const BlockPointerType *ToBlockPtr =
2483 ToType->getAs<BlockPointerType>()) {
2484 // Objective C++: We're able to convert from a pointer to any object
2485 // to a block pointer type.
2486 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
2487 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2488 return true;
2489 }
2490 ToPointeeType = ToBlockPtr->getPointeeType();
2491 }
2492 else if (FromType->getAs<BlockPointerType>() &&
2493 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
2494 // Objective C++: We're able to convert from a block pointer type to a
2495 // pointer to any object.
2496 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2497 return true;
2498 }
2499 else
2500 return false;
2501
2502 QualType FromPointeeType;
2503 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
2504 FromPointeeType = FromCPtr->getPointeeType();
2505 else if (const BlockPointerType *FromBlockPtr =
2506 FromType->getAs<BlockPointerType>())
2507 FromPointeeType = FromBlockPtr->getPointeeType();
2508 else
2509 return false;
2510
2511 // If we have pointers to pointers, recursively check whether this
2512 // is an Objective-C conversion.
2513 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2514 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2515 IncompatibleObjC)) {
2516 // We always complain about this conversion.
2517 IncompatibleObjC = true;
2518 ConvertedType = Context.getPointerType(ConvertedType);
2519 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2520 return true;
2521 }
2522 // Allow conversion of pointee being objective-c pointer to another one;
2523 // as in I* to id.
2524 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2525 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2526 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2527 IncompatibleObjC)) {
2528
2529 ConvertedType = Context.getPointerType(ConvertedType);
2530 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
2531 return true;
2532 }
2533
2534 // If we have pointers to functions or blocks, check whether the only
2535 // differences in the argument and result types are in Objective-C
2536 // pointer conversions. If so, we permit the conversion (but
2537 // complain about it).
2538 const FunctionProtoType *FromFunctionType
2539 = FromPointeeType->getAs<FunctionProtoType>();
2540 const FunctionProtoType *ToFunctionType
2541 = ToPointeeType->getAs<FunctionProtoType>();
2542 if (FromFunctionType && ToFunctionType) {
2543 // If the function types are exactly the same, this isn't an
2544 // Objective-C pointer conversion.
2545 if (Context.getCanonicalType(FromPointeeType)
2546 == Context.getCanonicalType(ToPointeeType))
2547 return false;
2548
2549 // Perform the quick checks that will tell us whether these
2550 // function types are obviously different.
2551 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2552 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2553 FromFunctionType->getMethodQuals() != ToFunctionType->getMethodQuals())
2554 return false;
2555
2556 bool HasObjCConversion = false;
2557 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2558 Context.getCanonicalType(ToFunctionType->getReturnType())) {
2559 // Okay, the types match exactly. Nothing to do.
2560 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2561 ToFunctionType->getReturnType(),
2562 ConvertedType, IncompatibleObjC)) {
2563 // Okay, we have an Objective-C pointer conversion.
2564 HasObjCConversion = true;
2565 } else {
2566 // Function types are too different. Abort.
2567 return false;
2568 }
2569
2570 // Check argument types.
2571 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2572 ArgIdx != NumArgs; ++ArgIdx) {
2573 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2574 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2575 if (Context.getCanonicalType(FromArgType)
2576 == Context.getCanonicalType(ToArgType)) {
2577 // Okay, the types match exactly. Nothing to do.
2578 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2579 ConvertedType, IncompatibleObjC)) {
2580 // Okay, we have an Objective-C pointer conversion.
2581 HasObjCConversion = true;
2582 } else {
2583 // Argument types are too different. Abort.
2584 return false;
2585 }
2586 }
2587
2588 if (HasObjCConversion) {
2589 // We had an Objective-C conversion. Allow this pointer
2590 // conversion, but complain about it.
2591 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
2592 IncompatibleObjC = true;
2593 return true;
2594 }
2595 }
2596
2597 return false;
2598}
2599
2600/// Determine whether this is an Objective-C writeback conversion,
2601/// used for parameter passing when performing automatic reference counting.
2602///
2603/// \param FromType The type we're converting form.
2604///
2605/// \param ToType The type we're converting to.
2606///
2607/// \param ConvertedType The type that will be produced after applying
2608/// this conversion.
2609bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2610 QualType &ConvertedType) {
2611 if (!getLangOpts().ObjCAutoRefCount ||
2612 Context.hasSameUnqualifiedType(FromType, ToType))
2613 return false;
2614
2615 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2616 QualType ToPointee;
2617 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2618 ToPointee = ToPointer->getPointeeType();
2619 else
2620 return false;
2621
2622 Qualifiers ToQuals = ToPointee.getQualifiers();
2623 if (!ToPointee->isObjCLifetimeType() ||
2624 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2625 !ToQuals.withoutObjCLifetime().empty())
2626 return false;
2627
2628 // Argument must be a pointer to __strong to __weak.
2629 QualType FromPointee;
2630 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2631 FromPointee = FromPointer->getPointeeType();
2632 else
2633 return false;
2634
2635 Qualifiers FromQuals = FromPointee.getQualifiers();
2636 if (!FromPointee->isObjCLifetimeType() ||
2637 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2638 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2639 return false;
2640
2641 // Make sure that we have compatible qualifiers.
2642 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2643 if (!ToQuals.compatiblyIncludes(FromQuals))
2644 return false;
2645
2646 // Remove qualifiers from the pointee type we're converting from; they
2647 // aren't used in the compatibility check belong, and we'll be adding back
2648 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2649 FromPointee = FromPointee.getUnqualifiedType();
2650
2651 // The unqualified form of the pointee types must be compatible.
2652 ToPointee = ToPointee.getUnqualifiedType();
2653 bool IncompatibleObjC;
2654 if (Context.typesAreCompatible(FromPointee, ToPointee))
2655 FromPointee = ToPointee;
2656 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2657 IncompatibleObjC))
2658 return false;
2659
2660 /// Construct the type we're converting to, which is a pointer to
2661 /// __autoreleasing pointee.
2662 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2663 ConvertedType = Context.getPointerType(FromPointee);
2664 return true;
2665}
2666
2667bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2668 QualType& ConvertedType) {
2669 QualType ToPointeeType;
2670 if (const BlockPointerType *ToBlockPtr =
2671 ToType->getAs<BlockPointerType>())
2672 ToPointeeType = ToBlockPtr->getPointeeType();
2673 else
2674 return false;
2675
2676 QualType FromPointeeType;
2677 if (const BlockPointerType *FromBlockPtr =
2678 FromType->getAs<BlockPointerType>())
2679 FromPointeeType = FromBlockPtr->getPointeeType();
2680 else
2681 return false;
2682 // We have pointer to blocks, check whether the only
2683 // differences in the argument and result types are in Objective-C
2684 // pointer conversions. If so, we permit the conversion.
2685
2686 const FunctionProtoType *FromFunctionType
2687 = FromPointeeType->getAs<FunctionProtoType>();
2688 const FunctionProtoType *ToFunctionType
2689 = ToPointeeType->getAs<FunctionProtoType>();
2690
2691 if (!FromFunctionType || !ToFunctionType)
2692 return false;
2693
2694 if (Context.hasSameType(FromPointeeType, ToPointeeType))
2695 return true;
2696
2697 // Perform the quick checks that will tell us whether these
2698 // function types are obviously different.
2699 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
2700 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2701 return false;
2702
2703 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2704 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2705 if (FromEInfo != ToEInfo)
2706 return false;
2707
2708 bool IncompatibleObjC = false;
2709 if (Context.hasSameType(FromFunctionType->getReturnType(),
2710 ToFunctionType->getReturnType())) {
2711 // Okay, the types match exactly. Nothing to do.
2712 } else {
2713 QualType RHS = FromFunctionType->getReturnType();
2714 QualType LHS = ToFunctionType->getReturnType();
2715 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
2716 !RHS.hasQualifiers() && LHS.hasQualifiers())
2717 LHS = LHS.getUnqualifiedType();
2718
2719 if (Context.hasSameType(RHS,LHS)) {
2720 // OK exact match.
2721 } else if (isObjCPointerConversion(RHS, LHS,
2722 ConvertedType, IncompatibleObjC)) {
2723 if (IncompatibleObjC)
2724 return false;
2725 // Okay, we have an Objective-C pointer conversion.
2726 }
2727 else
2728 return false;
2729 }
2730
2731 // Check argument types.
2732 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
2733 ArgIdx != NumArgs; ++ArgIdx) {
2734 IncompatibleObjC = false;
2735 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2736 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
2737 if (Context.hasSameType(FromArgType, ToArgType)) {
2738 // Okay, the types match exactly. Nothing to do.
2739 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2740 ConvertedType, IncompatibleObjC)) {
2741 if (IncompatibleObjC)
2742 return false;
2743 // Okay, we have an Objective-C pointer conversion.
2744 } else
2745 // Argument types are too different. Abort.
2746 return false;
2747 }
2748
2749 SmallVector<FunctionProtoType::ExtParameterInfo, 4> NewParamInfos;
2750 bool CanUseToFPT, CanUseFromFPT;
2751 if (!Context.mergeExtParameterInfo(ToFunctionType, FromFunctionType,
2752 CanUseToFPT, CanUseFromFPT,
2753 NewParamInfos))
2754 return false;
2755
2756 ConvertedType = ToType;
2757 return true;
2758}
2759
2760enum {
2761 ft_default,
2762 ft_different_class,
2763 ft_parameter_arity,
2764 ft_parameter_mismatch,
2765 ft_return_type,
2766 ft_qualifer_mismatch,
2767 ft_noexcept
2768};
2769
2770/// Attempts to get the FunctionProtoType from a Type. Handles
2771/// MemberFunctionPointers properly.
2772static const FunctionProtoType *tryGetFunctionProtoType(QualType FromType) {
2773 if (auto *FPT = FromType->getAs<FunctionProtoType>())
2774 return FPT;
2775
2776 if (auto *MPT = FromType->getAs<MemberPointerType>())
2777 return MPT->getPointeeType()->getAs<FunctionProtoType>();
2778
2779 return nullptr;
2780}
2781
2782/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2783/// function types. Catches different number of parameter, mismatch in
2784/// parameter types, and different return types.
2785void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2786 QualType FromType, QualType ToType) {
2787 // If either type is not valid, include no extra info.
2788 if (FromType.isNull() || ToType.isNull()) {
2789 PDiag << ft_default;
2790 return;
2791 }
2792
2793 // Get the function type from the pointers.
2794 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2795 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2796 *ToMember = ToType->getAs<MemberPointerType>();
2797 if (!Context.hasSameType(FromMember->getClass(), ToMember->getClass())) {
2798 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2799 << QualType(FromMember->getClass(), 0);
2800 return;
2801 }
2802 FromType = FromMember->getPointeeType();
2803 ToType = ToMember->getPointeeType();
2804 }
2805
2806 if (FromType->isPointerType())
2807 FromType = FromType->getPointeeType();
2808 if (ToType->isPointerType())
2809 ToType = ToType->getPointeeType();
2810
2811 // Remove references.
2812 FromType = FromType.getNonReferenceType();
2813 ToType = ToType.getNonReferenceType();
2814
2815 // Don't print extra info for non-specialized template functions.
2816 if (FromType->isInstantiationDependentType() &&
2817 !FromType->getAs<TemplateSpecializationType>()) {
2818 PDiag << ft_default;
2819 return;
2820 }
2821
2822 // No extra info for same types.
2823 if (Context.hasSameType(FromType, ToType)) {
2824 PDiag << ft_default;
2825 return;
2826 }
2827
2828 const FunctionProtoType *FromFunction = tryGetFunctionProtoType(FromType),
2829 *ToFunction = tryGetFunctionProtoType(ToType);
2830
2831 // Both types need to be function types.
2832 if (!FromFunction || !ToFunction) {
2833 PDiag << ft_default;
2834 return;
2835 }
2836
2837 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2838 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2839 << FromFunction->getNumParams();
2840 return;
2841 }
2842
2843 // Handle different parameter types.
2844 unsigned ArgPos;
2845 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2846 PDiag << ft_parameter_mismatch << ArgPos + 1
2847 << ToFunction->getParamType(ArgPos)
2848 << FromFunction->getParamType(ArgPos);
2849 return;
2850 }
2851
2852 // Handle different return type.
2853 if (!Context.hasSameType(FromFunction->getReturnType(),
2854 ToFunction->getReturnType())) {
2855 PDiag << ft_return_type << ToFunction->getReturnType()
2856 << FromFunction->getReturnType();
2857 return;
2858 }
2859
2860 if (FromFunction->getMethodQuals() != ToFunction->getMethodQuals()) {
2861 PDiag << ft_qualifer_mismatch << ToFunction->getMethodQuals()
2862 << FromFunction->getMethodQuals();
2863 return;
2864 }
2865
2866 // Handle exception specification differences on canonical type (in C++17
2867 // onwards).
2868 if (cast<FunctionProtoType>(FromFunction->getCanonicalTypeUnqualified())
2869 ->isNothrow() !=
2870 cast<FunctionProtoType>(ToFunction->getCanonicalTypeUnqualified())
2871 ->isNothrow()) {
2872 PDiag << ft_noexcept;
2873 return;
2874 }
2875
2876 // Unable to find a difference, so add no extra info.
2877 PDiag << ft_default;
2878}
2879
2880/// FunctionParamTypesAreEqual - This routine checks two function proto types
2881/// for equality of their argument types. Caller has already checked that
2882/// they have same number of arguments. If the parameters are different,
2883/// ArgPos will have the parameter index of the first different parameter.
2884bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2885 const FunctionProtoType *NewType,
2886 unsigned *ArgPos) {
2887 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2888 N = NewType->param_type_begin(),
2889 E = OldType->param_type_end();
2890 O && (O != E); ++O, ++N) {
2891 if (!Context.hasSameType(O->getUnqualifiedType(),
2892 N->getUnqualifiedType())) {
2893 if (ArgPos)
2894 *ArgPos = O - OldType->param_type_begin();
2895 return false;
2896 }
2897 }
2898 return true;
2899}
2900
2901/// CheckPointerConversion - Check the pointer conversion from the
2902/// expression From to the type ToType. This routine checks for
2903/// ambiguous or inaccessible derived-to-base pointer
2904/// conversions for which IsPointerConversion has already returned
2905/// true. It returns true and produces a diagnostic if there was an
2906/// error, or returns false otherwise.
2907bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
2908 CastKind &Kind,
2909 CXXCastPath& BasePath,
2910 bool IgnoreBaseAccess,
2911 bool Diagnose) {
2912 QualType FromType = From->getType();
2913 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
2914
2915 Kind = CK_BitCast;
2916
2917 if (Diagnose && !IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2918 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2919 Expr::NPCK_ZeroExpression) {
2920 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2921 DiagRuntimeBehavior(From->getExprLoc(), From,
2922 PDiag(diag::warn_impcast_bool_to_null_pointer)
2923 << ToType << From->getSourceRange());
2924 else if (!isUnevaluatedContext())
2925 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2926 << ToType << From->getSourceRange();
2927 }
2928 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2929 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
2930 QualType FromPointeeType = FromPtrType->getPointeeType(),
2931 ToPointeeType = ToPtrType->getPointeeType();
2932
2933 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2934 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
2935 // We must have a derived-to-base conversion. Check an
2936 // ambiguous or inaccessible conversion.
2937 unsigned InaccessibleID = 0;
2938 unsigned AmbigiousID = 0;
2939 if (Diagnose) {
2940 InaccessibleID = diag::err_upcast_to_inaccessible_base;
2941 AmbigiousID = diag::err_ambiguous_derived_to_base_conv;
2942 }
2943 if (CheckDerivedToBaseConversion(
2944 FromPointeeType, ToPointeeType, InaccessibleID, AmbigiousID,
2945 From->getExprLoc(), From->getSourceRange(), DeclarationName(),
2946 &BasePath, IgnoreBaseAccess))
2947 return true;
2948
2949 // The conversion was successful.
2950 Kind = CK_DerivedToBase;
2951 }
2952
2953 if (Diagnose && !IsCStyleOrFunctionalCast &&
2954 FromPointeeType->isFunctionType() && ToPointeeType->isVoidType()) {
2955 assert(getLangOpts().MSVCCompat &&
2956 "this should only be possible with MSVCCompat!");
2957 Diag(From->getExprLoc(), diag::ext_ms_impcast_fn_obj)
2958 << From->getSourceRange();
2959 }
2960 }
2961 } else if (const ObjCObjectPointerType *ToPtrType =
2962 ToType->getAs<ObjCObjectPointerType>()) {
2963 if (const ObjCObjectPointerType *FromPtrType =
2964 FromType->getAs<ObjCObjectPointerType>()) {
2965 // Objective-C++ conversions are always okay.
2966 // FIXME: We should have a different class of conversions for the
2967 // Objective-C++ implicit conversions.
2968 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
2969 return false;
2970 } else if (FromType->isBlockPointerType()) {
2971 Kind = CK_BlockPointerToObjCPointerCast;
2972 } else {
2973 Kind = CK_CPointerToObjCPointerCast;
2974 }
2975 } else if (ToType->isBlockPointerType()) {
2976 if (!FromType->isBlockPointerType())
2977 Kind = CK_AnyPointerToBlockPointerCast;
2978 }
2979
2980 // We shouldn't fall into this case unless it's valid for other
2981 // reasons.
2982 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2983 Kind = CK_NullToPointer;
2984
2985 return false;
2986}
2987
2988/// IsMemberPointerConversion - Determines whether the conversion of the
2989/// expression From, which has the (possibly adjusted) type FromType, can be
2990/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2991/// If so, returns true and places the converted type (that might differ from
2992/// ToType in its cv-qualifiers at some level) into ConvertedType.
2993bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
2994 QualType ToType,
2995 bool InOverloadResolution,
2996 QualType &ConvertedType) {
2997 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
2998 if (!ToTypePtr)
2999 return false;
3000
3001 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
3002 if (From->isNullPointerConstant(Context,
3003 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
3004 : Expr::NPC_ValueDependentIsNull)) {
3005 ConvertedType = ToType;
3006 return true;
3007 }
3008
3009 // Otherwise, both types have to be member pointers.
3010 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
3011 if (!FromTypePtr)
3012 return false;
3013
3014 // A pointer to member of B can be converted to a pointer to member of D,
3015 // where D is derived from B (C++ 4.11p2).
3016 QualType FromClass(FromTypePtr->getClass(), 0);
3017 QualType ToClass(ToTypePtr->getClass(), 0);
3018
3019 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
3020 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass)) {
3021 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
3022 ToClass.getTypePtr());
3023 return true;
3024 }
3025
3026 return false;
3027}
3028
3029/// CheckMemberPointerConversion - Check the member pointer conversion from the
3030/// expression From to the type ToType. This routine checks for ambiguous or
3031/// virtual or inaccessible base-to-derived member pointer conversions
3032/// for which IsMemberPointerConversion has already returned true. It returns
3033/// true and produces a diagnostic if there was an error, or returns false
3034/// otherwise.
3035bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
3036 CastKind &Kind,
3037 CXXCastPath &BasePath,
3038 bool IgnoreBaseAccess) {
3039 QualType FromType = From->getType();
3040 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
3041 if (!FromPtrType) {
3042 // This must be a null pointer to member pointer conversion
3043 assert(From->isNullPointerConstant(Context,
3044 Expr::NPC_ValueDependentIsNull) &&
3045 "Expr must be null pointer constant!");
3046 Kind = CK_NullToMemberPointer;
3047 return false;
3048 }
3049
3050 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
3051 assert(ToPtrType && "No member pointer cast has a target type "
3052 "that is not a member pointer.");
3053
3054 QualType FromClass = QualType(FromPtrType->getClass(), 0);
3055 QualType ToClass = QualType(ToPtrType->getClass(), 0);
3056
3057 // FIXME: What about dependent types?
3058 assert(FromClass->isRecordType() && "Pointer into non-class.");
3059 assert(ToClass->isRecordType() && "Pointer into non-class.");
3060
3061 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3062 /*DetectVirtual=*/true);
3063 bool DerivationOkay =
3064 IsDerivedFrom(From->getBeginLoc(), ToClass, FromClass, Paths);
3065 assert(DerivationOkay &&
3066 "Should not have been called if derivation isn't OK.");
3067 (void)DerivationOkay;
3068
3069 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
3070 getUnqualifiedType())) {
3071 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3072 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
3073 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
3074 return true;
3075 }
3076
3077 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
3078 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
3079 << FromClass << ToClass << QualType(VBase, 0)
3080 << From->getSourceRange();
3081 return true;
3082 }
3083
3084 if (!IgnoreBaseAccess)
3085 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
3086 Paths.front(),
3087 diag::err_downcast_from_inaccessible_base);
3088
3089 // Must be a base to derived member conversion.
3090 BuildBasePathArray(Paths, BasePath);
3091 Kind = CK_BaseToDerivedMemberPointer;
3092 return false;
3093}
3094
3095/// Determine whether the lifetime conversion between the two given
3096/// qualifiers sets is nontrivial.
3097static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
3098 Qualifiers ToQuals) {
3099 // Converting anything to const __unsafe_unretained is trivial.
3100 if (ToQuals.hasConst() &&
3101 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
3102 return false;
3103
3104 return true;
3105}
3106
3107/// IsQualificationConversion - Determines whether the conversion from
3108/// an rvalue of type FromType to ToType is a qualification conversion
3109/// (C++ 4.4).
3110///
3111/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
3112/// when the qualification conversion involves a change in the Objective-C
3113/// object lifetime.
3114bool
3115Sema::IsQualificationConversion(QualType FromType, QualType ToType,
3116 bool CStyle, bool &ObjCLifetimeConversion) {
3117 FromType = Context.getCanonicalType(FromType);
3118 ToType = Context.getCanonicalType(ToType);
3119 ObjCLifetimeConversion = false;
3120
3121 // If FromType and ToType are the same type, this is not a
3122 // qualification conversion.
3123 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
3124 return false;
3125
3126 // (C++ 4.4p4):
3127 // A conversion can add cv-qualifiers at levels other than the first
3128 // in multi-level pointers, subject to the following rules: [...]
3129 bool PreviousToQualsIncludeConst = true;
3130 bool UnwrappedAnyPointer = false;
3131 while (Context.UnwrapSimilarTypes(FromType, ToType)) {
3132 // Within each iteration of the loop, we check the qualifiers to
3133 // determine if this still looks like a qualification
3134 // conversion. Then, if all is well, we unwrap one more level of
3135 // pointers or pointers-to-members and do it all again
3136 // until there are no more pointers or pointers-to-members left to
3137 // unwrap.
3138 UnwrappedAnyPointer = true;
3139
3140 Qualifiers FromQuals = FromType.getQualifiers();
3141 Qualifiers ToQuals = ToType.getQualifiers();
3142
3143 // Ignore __unaligned qualifier if this type is void.
3144 if (ToType.getUnqualifiedType()->isVoidType())
3145 FromQuals.removeUnaligned();
3146
3147 // Objective-C ARC:
3148 // Check Objective-C lifetime conversions.
3149 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
3150 UnwrappedAnyPointer) {
3151 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
3152 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
3153 ObjCLifetimeConversion = true;
3154 FromQuals.removeObjCLifetime();
3155 ToQuals.removeObjCLifetime();
3156 } else {
3157 // Qualification conversions cannot cast between different
3158 // Objective-C lifetime qualifiers.
3159 return false;
3160 }
3161 }
3162
3163 // Allow addition/removal of GC attributes but not changing GC attributes.
3164 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
3165 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
3166 FromQuals.removeObjCGCAttr();
3167 ToQuals.removeObjCGCAttr();
3168 }
3169
3170 // -- for every j > 0, if const is in cv 1,j then const is in cv
3171 // 2,j, and similarly for volatile.
3172 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
3173 return false;
3174
3175 // -- if the cv 1,j and cv 2,j are different, then const is in
3176 // every cv for 0 < k < j.
3177 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
3178 && !PreviousToQualsIncludeConst)
3179 return false;
3180
3181 // Keep track of whether all prior cv-qualifiers in the "to" type
3182 // include const.
3183 PreviousToQualsIncludeConst
3184 = PreviousToQualsIncludeConst && ToQuals.hasConst();
3185 }
3186
3187 // Allows address space promotion by language rules implemented in
3188 // Type::Qualifiers::isAddressSpaceSupersetOf.
3189 Qualifiers FromQuals = FromType.getQualifiers();
3190 Qualifiers ToQuals = ToType.getQualifiers();
3191 if (!ToQuals.isAddressSpaceSupersetOf(FromQuals) &&
3192 !FromQuals.isAddressSpaceSupersetOf(ToQuals)) {
3193 return false;
3194 }
3195
3196 // We are left with FromType and ToType being the pointee types
3197 // after unwrapping the original FromType and ToType the same number
3198 // of types. If we unwrapped any pointers, and if FromType and
3199 // ToType have the same unqualified type (since we checked
3200 // qualifiers above), then this is a qualification conversion.
3201 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
3202}
3203
3204/// - Determine whether this is a conversion from a scalar type to an
3205/// atomic type.
3206///
3207/// If successful, updates \c SCS's second and third steps in the conversion
3208/// sequence to finish the conversion.
3209static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
3210 bool InOverloadResolution,
3211 StandardConversionSequence &SCS,
3212 bool CStyle) {
3213 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
3214 if (!ToAtomic)
3215 return false;
3216
3217 StandardConversionSequence InnerSCS;
3218 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
3219 InOverloadResolution, InnerSCS,
3220 CStyle, /*AllowObjCWritebackConversion=*/false))
3221 return false;
3222
3223 SCS.Second = InnerSCS.Second;
3224 SCS.setToType(1, InnerSCS.getToType(1));
3225 SCS.Third = InnerSCS.Third;
3226 SCS.QualificationIncludesObjCLifetime
3227 = InnerSCS.QualificationIncludesObjCLifetime;
3228 SCS.setToType(2, InnerSCS.getToType(2));
3229 return true;
3230}
3231
3232static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
3233 CXXConstructorDecl *Constructor,
3234 QualType Type) {
3235 const FunctionProtoType *CtorType =
3236 Constructor->getType()->getAs<FunctionProtoType>();
3237 if (CtorType->getNumParams() > 0) {
3238 QualType FirstArg = CtorType->getParamType(0);
3239 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
3240 return true;
3241 }
3242 return false;
3243}
3244
3245static OverloadingResult
3246IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
3247 CXXRecordDecl *To,
3248 UserDefinedConversionSequence &User,
3249 OverloadCandidateSet &CandidateSet,
3250 bool AllowExplicit) {
3251 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3252 for (auto *D : S.LookupConstructors(To)) {
3253 auto Info = getConstructorInfo(D);
3254 if (!Info)
3255 continue;
3256
3257 bool Usable = !Info.Constructor->isInvalidDecl() &&
3258 S.isInitListConstructor(Info.Constructor) &&
3259 (AllowExplicit || !Info.Constructor->isExplicit());
3260 if (Usable) {
3261 // If the first argument is (a reference to) the target type,
3262 // suppress conversions.
3263 bool SuppressUserConversions = isFirstArgumentCompatibleWithType(
3264 S.Context, Info.Constructor, ToType);
3265 if (Info.ConstructorTmpl)
3266 S.AddTemplateOverloadCandidate(Info.ConstructorTmpl, Info.FoundDecl,
3267 /*ExplicitArgs*/ nullptr, From,
3268 CandidateSet, SuppressUserConversions,
3269 /*PartialOverloading*/ false,
3270 AllowExplicit);
3271 else
3272 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl, From,
3273 CandidateSet, SuppressUserConversions,
3274 /*PartialOverloading*/ false, AllowExplicit);
3275 }
3276 }
3277
3278 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3279
3280 OverloadCandidateSet::iterator Best;
3281 switch (auto Result =
3282 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3283 case OR_Deleted:
3284 case OR_Success: {
3285 // Record the standard conversion we used and the conversion function.
3286 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
3287 QualType ThisType = Constructor->getThisType();
3288 // Initializer lists don't have conversions as such.
3289 User.Before.setAsIdentityConversion();
3290 User.HadMultipleCandidates = HadMultipleCandidates;
3291 User.ConversionFunction = Constructor;
3292 User.FoundConversionFunction = Best->FoundDecl;
3293 User.After.setAsIdentityConversion();
3294 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3295 User.After.setAllToTypes(ToType);
3296 return Result;
3297 }
3298
3299 case OR_No_Viable_Function:
3300 return OR_No_Viable_Function;
3301 case OR_Ambiguous:
3302 return OR_Ambiguous;
3303 }
3304
3305 llvm_unreachable("Invalid OverloadResult!");
3306}
3307
3308/// Determines whether there is a user-defined conversion sequence
3309/// (C++ [over.ics.user]) that converts expression From to the type
3310/// ToType. If such a conversion exists, User will contain the
3311/// user-defined conversion sequence that performs such a conversion
3312/// and this routine will return true. Otherwise, this routine returns
3313/// false and User is unspecified.
3314///
3315/// \param AllowExplicit true if the conversion should consider C++0x
3316/// "explicit" conversion functions as well as non-explicit conversion
3317/// functions (C++0x [class.conv.fct]p2).
3318///
3319/// \param AllowObjCConversionOnExplicit true if the conversion should
3320/// allow an extra Objective-C pointer conversion on uses of explicit
3321/// constructors. Requires \c AllowExplicit to also be set.
3322static OverloadingResult
3323IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
3324 UserDefinedConversionSequence &User,
3325 OverloadCandidateSet &CandidateSet,
3326 bool AllowExplicit,
3327 bool AllowObjCConversionOnExplicit) {
3328 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
3329 CandidateSet.clear(OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3330
3331 // Whether we will only visit constructors.
3332 bool ConstructorsOnly = false;
3333
3334 // If the type we are conversion to is a class type, enumerate its
3335 // constructors.
3336 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
3337 // C++ [over.match.ctor]p1:
3338 // When objects of class type are direct-initialized (8.5), or
3339 // copy-initialized from an expression of the same or a
3340 // derived class type (8.5), overload resolution selects the
3341 // constructor. [...] For copy-initialization, the candidate
3342 // functions are all the converting constructors (12.3.1) of
3343 // that class. The argument list is the expression-list within
3344 // the parentheses of the initializer.
3345 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
3346 (From->getType()->getAs<RecordType>() &&
3347 S.IsDerivedFrom(From->getBeginLoc(), From->getType(), ToType)))
3348 ConstructorsOnly = true;
3349
3350 if (!S.isCompleteType(From->getExprLoc(), ToType)) {
3351 // We're not going to find any constructors.
3352 } else if (CXXRecordDecl *ToRecordDecl
3353 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
3354
3355 Expr **Args = &From;
3356 unsigned NumArgs = 1;
3357 bool ListInitializing = false;
3358 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
3359 // But first, see if there is an init-list-constructor that will work.
3360 OverloadingResult Result = IsInitializerListConstructorConversion(
3361 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3362 if (Result != OR_No_Viable_Function)
3363 return Result;
3364 // Never mind.
3365 CandidateSet.clear(
3366 OverloadCandidateSet::CSK_InitByUserDefinedConversion);
3367
3368 // If we're list-initializing, we pass the individual elements as
3369 // arguments, not the entire list.
3370 Args = InitList->getInits();
3371 NumArgs = InitList->getNumInits();
3372 ListInitializing = true;
3373 }
3374
3375 for (auto *D : S.LookupConstructors(ToRecordDecl)) {
3376 auto Info = getConstructorInfo(D);
3377 if (!Info)
3378 continue;
3379
3380 bool Usable = !Info.Constructor->isInvalidDecl();
3381 if (ListInitializing)
3382 Usable = Usable && (AllowExplicit || !Info.Constructor->isExplicit());
3383 else
3384 Usable = Usable &&
3385 Info.Constructor->isConvertingConstructor(AllowExplicit);
3386 if (Usable) {
3387 bool SuppressUserConversions = !ConstructorsOnly;
3388 if (SuppressUserConversions && ListInitializing) {
3389 SuppressUserConversions = false;
3390 if (NumArgs == 1) {
3391 // If the first argument is (a reference to) the target type,
3392 // suppress conversions.
3393 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3394 S.Context, Info.Constructor, ToType);
3395 }
3396 }
3397 if (Info.ConstructorTmpl)
3398 S.AddTemplateOverloadCandidate(
3399 Info.ConstructorTmpl, Info.FoundDecl,
3400 /*ExplicitArgs*/ nullptr, llvm::makeArrayRef(Args, NumArgs),
3401 CandidateSet, SuppressUserConversions,
3402 /*PartialOverloading*/ false, AllowExplicit);
3403 else
3404 // Allow one user-defined conversion when user specifies a
3405 // From->ToType conversion via an static cast (c-style, etc).
3406 S.AddOverloadCandidate(Info.Constructor, Info.FoundDecl,
3407 llvm::makeArrayRef(Args, NumArgs),
3408 CandidateSet, SuppressUserConversions,
3409 /*PartialOverloading*/ false, AllowExplicit);
3410 }
3411 }
3412 }
3413 }
3414
3415 // Enumerate conversion functions, if we're allowed to.
3416 if (ConstructorsOnly || isa<InitListExpr>(From)) {
3417 } else if (!S.isCompleteType(From->getBeginLoc(), From->getType())) {
3418 // No conversion functions from incomplete types.
3419 } else if (const RecordType *FromRecordType =
3420 From->getType()->getAs<RecordType>()) {
3421 if (CXXRecordDecl *FromRecordDecl
3422 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3423 // Add all of the conversion functions as candidates.
3424 const auto &Conversions = FromRecordDecl->getVisibleConversionFunctions();
3425 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
3426 DeclAccessPair FoundDecl = I.getPair();
3427 NamedDecl *D = FoundDecl.getDecl();
3428 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3429 if (isa<UsingShadowDecl>(D))
3430 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3431
3432 CXXConversionDecl *Conv;
3433 FunctionTemplateDecl *ConvTemplate;
3434 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3435 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3436 else
3437 Conv = cast<CXXConversionDecl>(D);
3438
3439 if (AllowExplicit || !Conv->isExplicit()) {
3440 if (ConvTemplate)
3441 S.AddTemplateConversionCandidate(
3442 ConvTemplate, FoundDecl, ActingContext, From, ToType,
3443 CandidateSet, AllowObjCConversionOnExplicit, AllowExplicit);
3444 else
3445 S.AddConversionCandidate(
3446 Conv, FoundDecl, ActingContext, From, ToType, CandidateSet,
3447 AllowObjCConversionOnExplicit, AllowExplicit);
3448 }
3449 }
3450 }
3451 }
3452
3453 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3454
3455 OverloadCandidateSet::iterator Best;
3456 switch (auto Result =
3457 CandidateSet.BestViableFunction(S, From->getBeginLoc(), Best)) {
3458 case OR_Success:
3459 case OR_Deleted:
3460 // Record the standard conversion we used and the conversion function.
3461 if (CXXConstructorDecl *Constructor
3462 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3463 // C++ [over.ics.user]p1:
3464 // If the user-defined conversion is specified by a
3465 // constructor (12.3.1), the initial standard conversion
3466 // sequence converts the source type to the type required by
3467 // the argument of the constructor.
3468 //
3469 QualType ThisType = Constructor->getThisType();
3470 if (isa<InitListExpr>(From)) {
3471 // Initializer lists don't have conversions as such.
3472 User.Before.setAsIdentityConversion();
3473 } else {
3474 if (Best->Conversions[0].isEllipsis())
3475 User.EllipsisConversion = true;
3476 else {
3477 User.Before = Best->Conversions[0].Standard;
3478 User.EllipsisConversion = false;
3479 }
3480 }
3481 User.HadMultipleCandidates = HadMultipleCandidates;
3482 User.ConversionFunction = Constructor;
3483 User.FoundConversionFunction = Best->FoundDecl;
3484 User.After.setAsIdentityConversion();
3485 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3486 User.After.setAllToTypes(ToType);
3487 return Result;
3488 }
3489 if (CXXConversionDecl *Conversion
3490 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3491 // C++ [over.ics.user]p1:
3492 //
3493 // [...] If the user-defined conversion is specified by a
3494 // conversion function (12.3.2), the initial standard
3495 // conversion sequence converts the source type to the
3496 // implicit object parameter of the conversion function.
3497 User.Before = Best->Conversions[0].Standard;
3498 User.HadMultipleCandidates = HadMultipleCandidates;
3499 User.ConversionFunction = Conversion;
3500 User.FoundConversionFunction = Best->FoundDecl;
3501 User.EllipsisConversion = false;
3502
3503 // C++ [over.ics.user]p2:
3504 // The second standard conversion sequence converts the
3505 // result of the user-defined conversion to the target type
3506 // for the sequence. Since an implicit conversion sequence
3507 // is an initialization, the special rules for
3508 // initialization by user-defined conversion apply when
3509 // selecting the best user-defined conversion for a
3510 // user-defined conversion sequence (see 13.3.3 and
3511 // 13.3.3.1).
3512 User.After = Best->FinalConversion;
3513 return Result;
3514 }
3515 llvm_unreachable("Not a constructor or conversion function?");
3516
3517 case OR_No_Viable_Function:
3518 return OR_No_Viable_Function;
3519
3520 case OR_Ambiguous:
3521 return OR_Ambiguous;
3522 }
3523
3524 llvm_unreachable("Invalid OverloadResult!");
3525}
3526
3527bool
3528Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
3529 ImplicitConversionSequence ICS;
3530 OverloadCandidateSet CandidateSet(From->getExprLoc(),
3531 OverloadCandidateSet::CSK_Normal);
3532 OverloadingResult OvResult =
3533 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
3534 CandidateSet, false, false);
3535
3536 if (!(OvResult == OR_Ambiguous ||
3537 (OvResult == OR_No_Viable_Function && !CandidateSet.empty())))
3538 return false;
3539
3540 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, From);
3541 if (OvResult == OR_Ambiguous)
3542 Diag(From->getBeginLoc(), diag::err_typecheck_ambiguous_condition)
3543 << From->getType() << ToType << From->getSourceRange();
3544 else { // OR_No_Viable_Function && !CandidateSet.empty()
3545 if (!RequireCompleteType(From->getBeginLoc(), ToType,
3546 diag::err_typecheck_nonviable_condition_incomplete,
3547 From->getType(), From->getSourceRange()))
3548 Diag(From->getBeginLoc(), diag::err_typecheck_nonviable_condition)
3549 << false << From->getType() << From->getSourceRange() << ToType;
3550 }
3551
3552 CandidateSet.NoteCandidates(
3553 *this, From, Cands);
3554 return true;
3555}
3556
3557/// Compare the user-defined conversion functions or constructors
3558/// of two user-defined conversion sequences to determine whether any ordering
3559/// is possible.
3560static ImplicitConversionSequence::CompareKind
3561compareConversionFunctions(Sema &S, FunctionDecl *Function1,
3562 FunctionDecl *Function2) {
3563 if (!S.getLangOpts().ObjC || !S.getLangOpts().CPlusPlus11)
3564 return ImplicitConversionSequence::Indistinguishable;
3565
3566 // Objective-C++:
3567 // If both conversion functions are implicitly-declared conversions from
3568 // a lambda closure type to a function pointer and a block pointer,
3569 // respectively, always prefer the conversion to a function pointer,
3570 // because the function pointer is more lightweight and is more likely
3571 // to keep code working.
3572 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
3573 if (!Conv1)
3574 return ImplicitConversionSequence::Indistinguishable;
3575
3576 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3577 if (!Conv2)
3578 return ImplicitConversionSequence::Indistinguishable;
3579
3580 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3581 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3582 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3583 if (Block1 != Block2)
3584 return Block1 ? ImplicitConversionSequence::Worse
3585 : ImplicitConversionSequence::Better;
3586 }
3587
3588 return ImplicitConversionSequence::Indistinguishable;
3589}
3590
3591static bool hasDeprecatedStringLiteralToCharPtrConversion(
3592 const ImplicitConversionSequence &ICS) {
3593 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3594 (ICS.isUserDefined() &&
3595 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3596}
3597
3598/// CompareImplicitConversionSequences - Compare two implicit
3599/// conversion sequences to determine whether one is better than the
3600/// other or if they are indistinguishable (C++ 13.3.3.2).
3601static ImplicitConversionSequence::CompareKind
3602CompareImplicitConversionSequences(Sema &S, SourceLocation Loc,
3603 const ImplicitConversionSequence& ICS1,
3604 const ImplicitConversionSequence& ICS2)
3605{
3606 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3607 // conversion sequences (as defined in 13.3.3.1)
3608 // -- a standard conversion sequence (13.3.3.1.1) is a better
3609 // conversion sequence than a user-defined conversion sequence or
3610 // an ellipsis conversion sequence, and
3611 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3612 // conversion sequence than an ellipsis conversion sequence
3613 // (13.3.3.1.3).
3614 //
3615 // C++0x [over.best.ics]p10:
3616 // For the purpose of ranking implicit conversion sequences as
3617 // described in 13.3.3.2, the ambiguous conversion sequence is
3618 // treated as a user-defined sequence that is indistinguishable
3619 // from any other user-defined conversion sequence.
3620
3621 // String literal to 'char *' conversion has been deprecated in C++03. It has
3622 // been removed from C++11. We still accept this conversion, if it happens at
3623 // the best viable function. Otherwise, this conversion is considered worse
3624 // than ellipsis conversion. Consider this as an extension; this is not in the
3625 // standard. For example:
3626 //
3627 // int &f(...); // #1
3628 // void f(char*); // #2
3629 // void g() { int &r = f("foo"); }
3630 //
3631 // In C++03, we pick #2 as the best viable function.
3632 // In C++11, we pick #1 as the best viable function, because ellipsis
3633 // conversion is better than string-literal to char* conversion (since there
3634 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3635 // convert arguments, #2 would be the best viable function in C++11.
3636 // If the best viable function has this conversion, a warning will be issued
3637 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3638
3639 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3640 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3641 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3642 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3643 ? ImplicitConversionSequence::Worse
3644 : ImplicitConversionSequence::Better;
3645
3646 if (ICS1.getKindRank() < ICS2.getKindRank())
3647 return ImplicitConversionSequence::Better;
3648 if (ICS2.getKindRank() < ICS1.getKindRank())
3649 return ImplicitConversionSequence::Worse;
3650
3651 // The following checks require both conversion sequences to be of
3652 // the same kind.
3653 if (ICS1.getKind() != ICS2.getKind())
3654 return ImplicitConversionSequence::Indistinguishable;
3655
3656 ImplicitConversionSequence::CompareKind Result =
3657 ImplicitConversionSequence::Indistinguishable;
3658
3659 // Two implicit conversion sequences of the same form are
3660 // indistinguishable conversion sequences unless one of the
3661 // following rules apply: (C++ 13.3.3.2p3):
3662
3663 // List-initialization sequence L1 is a better conversion sequence than
3664 // list-initialization sequence L2 if:
3665 // - L1 converts to std::initializer_list<X> for some X and L2 does not, or,
3666 // if not that,
3667 // - L1 converts to type "array of N1 T", L2 converts to type "array of N2 T",
3668 // and N1 is smaller than N2.,
3669 // even if one of the other rules in this paragraph would otherwise apply.
3670 if (!ICS1.isBad()) {
3671 if (ICS1.isStdInitializerListElement() &&
3672 !ICS2.isStdInitializerListElement())
3673 return ImplicitConversionSequence::Better;
3674 if (!ICS1.isStdInitializerListElement() &&
3675 ICS2.isStdInitializerListElement())
3676 return ImplicitConversionSequence::Worse;
3677 }
3678
3679 if (ICS1.isStandard())
3680 // Standard conversion sequence S1 is a better conversion sequence than
3681 // standard conversion sequence S2 if [...]
3682 Result = CompareStandardConversionSequences(S, Loc,
3683 ICS1.Standard, ICS2.Standard);
3684 else if (ICS1.isUserDefined()) {
3685 // User-defined conversion sequence U1 is a better conversion
3686 // sequence than another user-defined conversion sequence U2 if
3687 // they contain the same user-defined conversion function or
3688 // constructor and if the second standard conversion sequence of
3689 // U1 is better than the second standard conversion sequence of
3690 // U2 (C++ 13.3.3.2p3).
3691 if (ICS1.UserDefined.ConversionFunction ==
3692 ICS2.UserDefined.ConversionFunction)
3693 Result = CompareStandardConversionSequences(S, Loc,
3694 ICS1.UserDefined.After,
3695 ICS2.UserDefined.After);
3696 else
3697 Result = compareConversionFunctions(S,
3698 ICS1.UserDefined.ConversionFunction,
3699 ICS2.UserDefined.ConversionFunction);
3700 }
3701
3702 return Result;
3703}
3704
3705// Per 13.3.3.2p3, compare the given standard conversion sequences to
3706// determine if one is a proper subset of the other.
3707static ImplicitConversionSequence::CompareKind
3708compareStandardConversionSubsets(ASTContext &Context,
3709 const StandardConversionSequence& SCS1,
3710 const StandardConversionSequence& SCS2) {
3711 ImplicitConversionSequence::CompareKind Result
3712 = ImplicitConversionSequence::Indistinguishable;
3713
3714 // the identity conversion sequence is considered to be a subsequence of
3715 // any non-identity conversion sequence
3716 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3717 return ImplicitConversionSequence::Better;
3718 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3719 return ImplicitConversionSequence::Worse;
3720
3721 if (SCS1.Second != SCS2.Second) {
3722 if (SCS1.Second == ICK_Identity)
3723 Result = ImplicitConversionSequence::Better;
3724 else if (SCS2.Second == ICK_Identity)
3725 Result = ImplicitConversionSequence::Worse;
3726 else
3727 return ImplicitConversionSequence::Indistinguishable;
3728 } else if (!Context.hasSimilarType(SCS1.getToType(1), SCS2.getToType(1)))
3729 return ImplicitConversionSequence::Indistinguishable;
3730
3731 if (SCS1.Third == SCS2.Third) {
3732 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3733 : ImplicitConversionSequence::Indistinguishable;
3734 }
3735
3736 if (SCS1.Third == ICK_Identity)
3737 return Result == ImplicitConversionSequence::Worse
3738 ? ImplicitConversionSequence::Indistinguishable
3739 : ImplicitConversionSequence::Better;
3740
3741 if (SCS2.Third == ICK_Identity)
3742 return Result == ImplicitConversionSequence::Better
3743 ? ImplicitConversionSequence::Indistinguishable
3744 : ImplicitConversionSequence::Worse;
3745
3746 return ImplicitConversionSequence::Indistinguishable;
3747}
3748
3749/// Determine whether one of the given reference bindings is better
3750/// than the other based on what kind of bindings they are.
3751static bool
3752isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3753 const StandardConversionSequence &SCS2) {
3754 // C++0x [over.ics.rank]p3b4:
3755 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3756 // implicit object parameter of a non-static member function declared
3757 // without a ref-qualifier, and *either* S1 binds an rvalue reference
3758 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
3759 // lvalue reference to a function lvalue and S2 binds an rvalue
3760 // reference*.
3761 //
3762 // FIXME: Rvalue references. We're going rogue with the above edits,
3763 // because the semantics in the current C++0x working paper (N3225 at the
3764 // time of this writing) break the standard definition of std::forward
3765 // and std::reference_wrapper when dealing with references to functions.
3766 // Proposed wording changes submitted to CWG for consideration.
3767 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3768 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3769 return false;
3770
3771 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3772 SCS2.IsLvalueReference) ||
3773 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3774 !SCS2.IsLvalueReference && SCS2.BindsToFunctionLvalue);
3775}
3776
3777/// CompareStandardConversionSequences - Compare two standard
3778/// conversion sequences to determine whether one is better than the
3779/// other or if they are indistinguishable (C++ 13.3.3.2p3).
3780static ImplicitConversionSequence::CompareKind
3781CompareStandardConversionSequences(Sema &S, SourceLocation Loc,
3782 const StandardConversionSequence& SCS1,
3783 const StandardConversionSequence& SCS2)
3784{
3785 // Standard conversion sequence S1 is a better conversion sequence
3786 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3787
3788 // -- S1 is a proper subsequence of S2 (comparing the conversion
3789 // sequences in the canonical form defined by 13.3.3.1.1,
3790 // excluding any Lvalue Transformation; the identity conversion
3791 // sequence is considered to be a subsequence of any
3792 // non-identity conversion sequence) or, if not that,
3793 if (ImplicitConversionSequence::CompareKind CK
3794 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
3795 return CK;
3796
3797 // -- the rank of S1 is better than the rank of S2 (by the rules
3798 // defined below), or, if not that,
3799 ImplicitConversionRank Rank1 = SCS1.getRank();
3800 ImplicitConversionRank Rank2 = SCS2.getRank();
3801 if (Rank1 < Rank2)
3802 return ImplicitConversionSequence::Better;
3803 else if (Rank2 < Rank1)
3804 return ImplicitConversionSequence::Worse;
3805
3806 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3807 // are indistinguishable unless one of the following rules
3808 // applies:
3809
3810 // A conversion that is not a conversion of a pointer, or
3811 // pointer to member, to bool is better than another conversion
3812 // that is such a conversion.
3813 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3814 return SCS2.isPointerConversionToBool()
3815 ? ImplicitConversionSequence::Better
3816 : ImplicitConversionSequence::Worse;
3817
3818 // C++ [over.ics.rank]p4b2:
3819 //
3820 // If class B is derived directly or indirectly from class A,
3821 // conversion of B* to A* is better than conversion of B* to
3822 // void*, and conversion of A* to void* is better than conversion
3823 // of B* to void*.
3824 bool SCS1ConvertsToVoid
3825 = SCS1.isPointerConversionToVoidPointer(S.Context);
3826 bool SCS2ConvertsToVoid
3827 = SCS2.isPointerConversionToVoidPointer(S.Context);
3828 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3829 // Exactly one of the conversion sequences is a conversion to
3830 // a void pointer; it's the worse conversion.
3831 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3832 : ImplicitConversionSequence::Worse;
3833 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3834 // Neither conversion sequence converts to a void pointer; compare
3835 // their derived-to-base conversions.
3836 if (ImplicitConversionSequence::CompareKind DerivedCK
3837 = CompareDerivedToBaseConversions(S, Loc, SCS1, SCS2))
3838 return DerivedCK;
3839 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3840 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
3841 // Both conversion sequences are conversions to void
3842 // pointers. Compare the source types to determine if there's an
3843 // inheritance relationship in their sources.
3844 QualType FromType1 = SCS1.getFromType();
3845 QualType FromType2 = SCS2.getFromType();
3846
3847 // Adjust the types we're converting from via the array-to-pointer
3848 // conversion, if we need to.
3849 if (SCS1.First == ICK_Array_To_Pointer)
3850 FromType1 = S.Context.getArrayDecayedType(FromType1);
3851 if (SCS2.First == ICK_Array_To_Pointer)
3852 FromType2 = S.Context.getArrayDecayedType(FromType2);
3853
3854 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3855 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
3856
3857 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
3858 return ImplicitConversionSequence::Better;
3859 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
3860 return ImplicitConversionSequence::Worse;
3861
3862 // Objective-C++: If one interface is more specific than the
3863 // other, it is the better one.
3864 const ObjCObjectPointerType* FromObjCPtr1
3865 = FromType1->getAs<ObjCObjectPointerType>();
3866 const ObjCObjectPointerType* FromObjCPtr2
3867 = FromType2->getAs<ObjCObjectPointerType>();
3868 if (FromObjCPtr1 && FromObjCPtr2) {
3869 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3870 FromObjCPtr2);
3871 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3872 FromObjCPtr1);
3873 if (AssignLeft != AssignRight) {
3874 return AssignLeft? ImplicitConversionSequence::Better
3875 : ImplicitConversionSequence::Worse;
3876 }
3877 }
3878 }
3879
3880 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3881 // bullet 3).
3882 if (ImplicitConversionSequence::CompareKind QualCK
3883 = CompareQualificationConversions(S, SCS1, SCS2))
3884 return QualCK;
3885
3886 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
3887 // Check for a better reference binding based on the kind of bindings.
3888 if (isBetterReferenceBindingKind(SCS1, SCS2))
3889 return ImplicitConversionSequence::Better;
3890 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3891 return ImplicitConversionSequence::Worse;
3892
3893 // C++ [over.ics.rank]p3b4:
3894 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3895 // which the references refer are the same type except for
3896 // top-level cv-qualifiers, and the type to which the reference
3897 // initialized by S2 refers is more cv-qualified than the type
3898 // to which the reference initialized by S1 refers.
3899 QualType T1 = SCS1.getToType(2);
3900 QualType T2 = SCS2.getToType(2);
3901 T1 = S.Context.getCanonicalType(T1);
3902 T2 = S.Context.getCanonicalType(T2);
3903 Qualifiers T1Quals, T2Quals;
3904 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3905 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
3906 if (UnqualT1 == UnqualT2) {
3907 // Objective-C++ ARC: If the references refer to objects with different
3908 // lifetimes, prefer bindings that don't change lifetime.
3909 if (SCS1.ObjCLifetimeConversionBinding !=
3910 SCS2.ObjCLifetimeConversionBinding) {
3911 return SCS1.ObjCLifetimeConversionBinding
3912 ? ImplicitConversionSequence::Worse
3913 : ImplicitConversionSequence::Better;
3914 }
3915
3916 // If the type is an array type, promote the element qualifiers to the
3917 // type for comparison.
3918 if (isa<ArrayType>(T1) && T1Quals)
3919 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
3920 if (isa<ArrayType>(T2) && T2Quals)
3921 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
3922 if (T2.isMoreQualifiedThan(T1))
3923 return ImplicitConversionSequence::Better;
3924 else if (T1.isMoreQualifiedThan(T2))
3925 return ImplicitConversionSequence::Worse;
3926 }
3927 }
3928
3929 // In Microsoft mode, prefer an integral conversion to a
3930 // floating-to-integral conversion if the integral conversion
3931 // is between types of the same size.
3932 // For example:
3933 // void f(float);
3934 // void f(int);
3935 // int main {
3936 // long a;
3937 // f(a);
3938 // }
3939 // Here, MSVC will call f(int) instead of generating a compile error
3940 // as clang will do in standard mode.
3941 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3942 SCS2.Second == ICK_Floating_Integral &&
3943 S.Context.getTypeSize(SCS1.getFromType()) ==
3944 S.Context.getTypeSize(SCS1.getToType(2)))
3945 return ImplicitConversionSequence::Better;
3946
3947 // Prefer a compatible vector conversion over a lax vector conversion
3948 // For example:
3949 //
3950 // typedef float __v4sf __attribute__((__vector_size__(16)));
3951 // void f(vector float);
3952 // void f(vector signed int);
3953 // int main() {
3954 // __v4sf a;
3955 // f(a);
3956 // }
3957 // Here, we'd like to choose f(vector float) and not
3958 // report an ambiguous call error
3959 if (SCS1.Second == ICK_Vector_Conversion &&
3960 SCS2.Second == ICK_Vector_Conversion) {
3961 bool SCS1IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3962 SCS1.getFromType(), SCS1.getToType(2));
3963 bool SCS2IsCompatibleVectorConversion = S.Context.areCompatibleVectorTypes(
3964 SCS2.getFromType(), SCS2.getToType(2));
3965
3966 if (SCS1IsCompatibleVectorConversion != SCS2IsCompatibleVectorConversion)
3967 return SCS1IsCompatibleVectorConversion
3968 ? ImplicitConversionSequence::Better
3969 : ImplicitConversionSequence::Worse;
3970 }
3971
3972 return ImplicitConversionSequence::Indistinguishable;
3973}
3974
3975/// CompareQualificationConversions - Compares two standard conversion
3976/// sequences to determine whether they can be ranked based on their
3977/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3978static ImplicitConversionSequence::CompareKind
3979CompareQualificationConversions(Sema &S,
3980 const StandardConversionSequence& SCS1,
3981 const StandardConversionSequence& SCS2) {
3982 // C++ 13.3.3.2p3:
3983 // -- S1 and S2 differ only in their qualification conversion and
3984 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3985 // cv-qualification signature of type T1 is a proper subset of
3986 // the cv-qualification signature of type T2, and S1 is not the
3987 // deprecated string literal array-to-pointer conversion (4.2).
3988 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3989 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3990 return ImplicitConversionSequence::Indistinguishable;
3991
3992 // FIXME: the example in the standard doesn't use a qualification
3993 // conversion (!)
3994 QualType T1 = SCS1.getToType(2);
3995 QualType T2 = SCS2.getToType(2);
3996 T1 = S.Context.getCanonicalType(T1);
3997 T2 = S.Context.getCanonicalType(T2);
3998 Qualifiers T1Quals, T2Quals;
3999 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
4000 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
4001
4002 // If the types are the same, we won't learn anything by unwrapped
4003 // them.
4004 if (UnqualT1 == UnqualT2)
4005 return ImplicitConversionSequence::Indistinguishable;
4006
4007 // If the type is an array type, promote the element qualifiers to the type
4008 // for comparison.
4009 if (isa<ArrayType>(T1) && T1Quals)
4010 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
4011 if (isa<ArrayType>(T2) && T2Quals)
4012 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
4013
4014 ImplicitConversionSequence::CompareKind Result
4015 = ImplicitConversionSequence::Indistinguishable;
4016
4017 // Objective-C++ ARC:
4018 // Prefer qualification conversions not involving a change in lifetime
4019 // to qualification conversions that do not change lifetime.
4020 if (SCS1.QualificationIncludesObjCLifetime !=
4021 SCS2.QualificationIncludesObjCLifetime) {
4022 Result = SCS1.QualificationIncludesObjCLifetime
4023 ? ImplicitConversionSequence::Worse
4024 : ImplicitConversionSequence::Better;
4025 }
4026
4027 while (S.Context.UnwrapSimilarTypes(T1, T2)) {
4028 // Within each iteration of the loop, we check the qualifiers to
4029 // determine if this still looks like a qualification
4030 // conversion. Then, if all is well, we unwrap one more level of
4031 // pointers or pointers-to-members and do it all again
4032 // until there are no more pointers or pointers-to-members left
4033 // to unwrap. This essentially mimics what
4034 // IsQualificationConversion does, but here we're checking for a
4035 // strict subset of qualifiers.
4036 if (T1.getQualifiers().withoutObjCLifetime() ==
4037 T2.getQualifiers().withoutObjCLifetime())
4038 // The qualifiers are the same, so this doesn't tell us anything
4039 // about how the sequences rank.
4040 // ObjC ownership quals are omitted above as they interfere with
4041 // the ARC overload rule.
4042 ;
4043 else if (T2.isMoreQualifiedThan(T1)) {
4044 // T1 has fewer qualifiers, so it could be the better sequence.
4045 if (Result == ImplicitConversionSequence::Worse)
4046 // Neither has qualifiers that are a subset of the other's
4047 // qualifiers.
4048 return ImplicitConversionSequence::Indistinguishable;
4049
4050 Result = ImplicitConversionSequence::Better;
4051 } else if (T1.isMoreQualifiedThan(T2)) {
4052 // T2 has fewer qualifiers, so it could be the better sequence.
4053 if (Result == ImplicitConversionSequence::Better)
4054 // Neither has qualifiers that are a subset of the other's
4055 // qualifiers.
4056 return ImplicitConversionSequence::Indistinguishable;
4057
4058 Result = ImplicitConversionSequence::Worse;
4059 } else {
4060 // Qualifiers are disjoint.
4061 return ImplicitConversionSequence::Indistinguishable;
4062 }
4063
4064 // If the types after this point are equivalent, we're done.
4065 if (S.Context.hasSameUnqualifiedType(T1, T2))
4066 break;
4067 }
4068
4069 // Check that the winning standard conversion sequence isn't using
4070 // the deprecated string literal array to pointer conversion.
4071 switch (Result) {
4072 case ImplicitConversionSequence::Better:
4073 if (SCS1.DeprecatedStringLiteralToCharPtr)
4074 Result = ImplicitConversionSequence::Indistinguishable;
4075 break;
4076
4077 case ImplicitConversionSequence::Indistinguishable:
4078 break;
4079
4080 case ImplicitConversionSequence::Worse:
4081 if (SCS2.DeprecatedStringLiteralToCharPtr)
4082 Result = ImplicitConversionSequence::Indistinguishable;
4083 break;
4084 }
4085
4086 return Result;
4087}
4088
4089/// CompareDerivedToBaseConversions - Compares two standard conversion
4090/// sequences to determine whether they can be ranked based on their
4091/// various kinds of derived-to-base conversions (C++
4092/// [over.ics.rank]p4b3). As part of these checks, we also look at
4093/// conversions between Objective-C interface types.
4094static ImplicitConversionSequence::CompareKind
4095CompareDerivedToBaseConversions(Sema &S, SourceLocation Loc,
4096 const StandardConversionSequence& SCS1,
4097 const StandardConversionSequence& SCS2) {
4098 QualType FromType1 = SCS1.getFromType();
4099 QualType ToType1 = SCS1.getToType(1);
4100 QualType FromType2 = SCS2.getFromType();
4101 QualType ToType2 = SCS2.getToType(1);
4102
4103 // Adjust the types we're converting from via the array-to-pointer
4104 // conversion, if we need to.
4105 if (SCS1.First == ICK_Array_To_Pointer)
4106 FromType1 = S.Context.getArrayDecayedType(FromType1);
4107 if (SCS2.First == ICK_Array_To_Pointer)
4108 FromType2 = S.Context.getArrayDecayedType(FromType2);
4109
4110 // Canonicalize all of the types.
4111 FromType1 = S.Context.getCanonicalType(FromType1);
4112 ToType1 = S.Context.getCanonicalType(ToType1);
4113 FromType2 = S.Context.getCanonicalType(FromType2);
4114 ToType2 = S.Context.getCanonicalType(ToType2);
4115
4116 // C++ [over.ics.rank]p4b3:
4117 //
4118 // If class B is derived directly or indirectly from class A and
4119 // class C is derived directly or indirectly from B,
4120 //
4121 // Compare based on pointer conversions.
4122 if (SCS1.Second == ICK_Pointer_Conversion &&
4123 SCS2.Second == ICK_Pointer_Conversion &&
4124 /*FIXME: Remove if Objective-C id conversions get their own rank*/
4125 FromType1->isPointerType() && FromType2->isPointerType() &&
4126 ToType1->isPointerType() && ToType2->isPointerType()) {
4127 QualType FromPointee1
4128 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4129 QualType ToPointee1
4130 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4131 QualType FromPointee2
4132 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4133 QualType ToPointee2
4134 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
4135
4136 // -- conversion of C* to B* is better than conversion of C* to A*,
4137 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4138 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4139 return ImplicitConversionSequence::Better;
4140 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4141 return ImplicitConversionSequence::Worse;
4142 }
4143
4144 // -- conversion of B* to A* is better than conversion of C* to A*,
4145 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
4146 if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4147 return ImplicitConversionSequence::Better;
4148 else if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4149 return ImplicitConversionSequence::Worse;
4150 }
4151 } else if (SCS1.Second == ICK_Pointer_Conversion &&
4152 SCS2.Second == ICK_Pointer_Conversion) {
4153 const ObjCObjectPointerType *FromPtr1
4154 = FromType1->getAs<ObjCObjectPointerType>();
4155 const ObjCObjectPointerType *FromPtr2
4156 = FromType2->getAs<ObjCObjectPointerType>();
4157 const ObjCObjectPointerType *ToPtr1
4158 = ToType1->getAs<ObjCObjectPointerType>();
4159 const ObjCObjectPointerType *ToPtr2
4160 = ToType2->getAs<ObjCObjectPointerType>();
4161
4162 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
4163 // Apply the same conversion ranking rules for Objective-C pointer types
4164 // that we do for C++ pointers to class types. However, we employ the
4165 // Objective-C pseudo-subtyping relationship used for assignment of
4166 // Objective-C pointer types.
4167 bool FromAssignLeft
4168 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
4169 bool FromAssignRight
4170 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
4171 bool ToAssignLeft
4172 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
4173 bool ToAssignRight
4174 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
4175
4176 // A conversion to an a non-id object pointer type or qualified 'id'
4177 // type is better than a conversion to 'id'.
4178 if (ToPtr1->isObjCIdType() &&
4179 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
4180 return ImplicitConversionSequence::Worse;
4181 if (ToPtr2->isObjCIdType() &&
4182 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
4183 return ImplicitConversionSequence::Better;
4184
4185 // A conversion to a non-id object pointer type is better than a
4186 // conversion to a qualified 'id' type
4187 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
4188 return ImplicitConversionSequence::Worse;
4189 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
4190 return ImplicitConversionSequence::Better;
4191
4192 // A conversion to an a non-Class object pointer type or qualified 'Class'
4193 // type is better than a conversion to 'Class'.
4194 if (ToPtr1->isObjCClassType() &&
4195 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
4196 return ImplicitConversionSequence::Worse;
4197 if (ToPtr2->isObjCClassType() &&
4198 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
4199 return ImplicitConversionSequence::Better;
4200
4201 // A conversion to a non-Class object pointer type is better than a
4202 // conversion to a qualified 'Class' type.
4203 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
4204 return ImplicitConversionSequence::Worse;
4205 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
4206 return ImplicitConversionSequence::Better;
4207
4208 // -- "conversion of C* to B* is better than conversion of C* to A*,"
4209 if (S.Context.hasSameType(FromType1, FromType2) &&
4210 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
4211 (ToAssignLeft != ToAssignRight)) {
4212 if (FromPtr1->isSpecialized()) {
4213 // "conversion of B<A> * to B * is better than conversion of B * to
4214 // C *.
4215 bool IsFirstSame =
4216 FromPtr1->getInterfaceDecl() == ToPtr1->getInterfaceDecl();
4217 bool IsSecondSame =
4218 FromPtr1->getInterfaceDecl() == ToPtr2->getInterfaceDecl();
4219 if (IsFirstSame) {
4220 if (!IsSecondSame)
4221 return ImplicitConversionSequence::Better;
4222 } else if (IsSecondSame)
4223 return ImplicitConversionSequence::Worse;
4224 }
4225 return ToAssignLeft? ImplicitConversionSequence::Worse
4226 : ImplicitConversionSequence::Better;
4227 }
4228
4229 // -- "conversion of B* to A* is better than conversion of C* to A*,"
4230 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
4231 (FromAssignLeft != FromAssignRight))
4232 return FromAssignLeft? ImplicitConversionSequence::Better
4233 : ImplicitConversionSequence::Worse;
4234 }
4235 }
4236
4237 // Ranking of member-pointer types.
4238 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
4239 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
4240 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
4241 const MemberPointerType * FromMemPointer1 =
4242 FromType1->getAs<MemberPointerType>();
4243 const MemberPointerType * ToMemPointer1 =
4244 ToType1->getAs<MemberPointerType>();
4245 const MemberPointerType * FromMemPointer2 =
4246 FromType2->getAs<MemberPointerType>();
4247 const MemberPointerType * ToMemPointer2 =
4248 ToType2->getAs<MemberPointerType>();
4249 const Type *FromPointeeType1 = FromMemPointer1->getClass();
4250 const Type *ToPointeeType1 = ToMemPointer1->getClass();
4251 const Type *FromPointeeType2 = FromMemPointer2->getClass();
4252 const Type *ToPointeeType2 = ToMemPointer2->getClass();
4253 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
4254 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
4255 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
4256 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
4257 // conversion of A::* to B::* is better than conversion of A::* to C::*,
4258 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
4259 if (S.IsDerivedFrom(Loc, ToPointee1, ToPointee2))
4260 return ImplicitConversionSequence::Worse;
4261 else if (S.IsDerivedFrom(Loc, ToPointee2, ToPointee1))
4262 return ImplicitConversionSequence::Better;
4263 }
4264 // conversion of B::* to C::* is better than conversion of A::* to C::*
4265 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
4266 if (S.IsDerivedFrom(Loc, FromPointee1, FromPointee2))
4267 return ImplicitConversionSequence::Better;
4268 else if (S.IsDerivedFrom(Loc, FromPointee2, FromPointee1))
4269 return ImplicitConversionSequence::Worse;
4270 }
4271 }
4272
4273 if (SCS1.Second == ICK_Derived_To_Base) {
4274 // -- conversion of C to B is better than conversion of C to A,
4275 // -- binding of an expression of type C to a reference of type
4276 // B& is better than binding an expression of type C to a
4277 // reference of type A&,
4278 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4279 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4280 if (S.IsDerivedFrom(Loc, ToType1, ToType2))
4281 return ImplicitConversionSequence::Better;
4282 else if (S.IsDerivedFrom(Loc, ToType2, ToType1))
4283 return ImplicitConversionSequence::Worse;
4284 }
4285
4286 // -- conversion of B to A is better than conversion of C to A.
4287 // -- binding of an expression of type B to a reference of type
4288 // A& is better than binding an expression of type C to a
4289 // reference of type A&,
4290 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
4291 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
4292 if (S.IsDerivedFrom(Loc, FromType2, FromType1))
4293 return ImplicitConversionSequence::Better;
4294 else if (S.IsDerivedFrom(Loc, FromType1, FromType2))
4295 return ImplicitConversionSequence::Worse;
4296 }
4297 }
4298
4299 return ImplicitConversionSequence::Indistinguishable;
4300}
4301
4302/// Determine whether the given type is valid, e.g., it is not an invalid
4303/// C++ class.
4304static bool isTypeValid(QualType T) {
4305 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
4306 return !Record->isInvalidDecl();
4307
4308 return true;
4309}
4310
4311/// CompareReferenceRelationship - Compare the two types T1 and T2 to
4312/// determine whether they are reference-related,
4313/// reference-compatible, reference-compatible with added
4314/// qualification, or incompatible, for use in C++ initialization by
4315/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
4316/// type, and the first type (T1) is the pointee type of the reference
4317/// type being initialized.
4318Sema::ReferenceCompareResult
4319Sema::CompareReferenceRelationship(SourceLocation Loc,
4320 QualType OrigT1, QualType OrigT2,
4321 bool &DerivedToBase,
4322 bool &ObjCConversion,
4323 bool &ObjCLifetimeConversion) {
4324 assert(!OrigT1->isReferenceType() &&
4325 "T1 must be the pointee type of the reference type");
4326 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4327
4328 QualType T1 = Context.getCanonicalType(OrigT1);
4329 QualType T2 = Context.getCanonicalType(OrigT2);
4330 Qualifiers T1Quals, T2Quals;
4331 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4332 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4333
4334 // C++ [dcl.init.ref]p4:
4335 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4336 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4337 // T1 is a base class of T2.
4338 DerivedToBase = false;
4339 ObjCConversion = false;
4340 ObjCLifetimeConversion = false;
4341 QualType ConvertedT2;
4342 if (UnqualT1 == UnqualT2) {
4343 // Nothing to do.
4344 } else if (isCompleteType(Loc, OrigT2) &&
4345 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4346 IsDerivedFrom(Loc, UnqualT2, UnqualT1))
4347 DerivedToBase = true;
4348 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4349 UnqualT2->isObjCObjectOrInterfaceType() &&
4350 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4351 ObjCConversion = true;
4352 else if (UnqualT2->isFunctionType() &&
4353 IsFunctionConversion(UnqualT2, UnqualT1, ConvertedT2))
4354 // C++1z [dcl.init.ref]p4:
4355 // cv1 T1" is reference-compatible with "cv2 T2" if [...] T2 is "noexcept
4356 // function" and T1 is "function"
4357 //
4358 // We extend this to also apply to 'noreturn', so allow any function
4359 // conversion between function types.
4360 return Ref_Compatible;
4361 else
4362 return Ref_Incompatible;
4363
4364 // At this point, we know that T1 and T2 are reference-related (at
4365 // least).
4366
4367 // If the type is an array type, promote the element qualifiers to the type
4368 // for comparison.
4369 if (isa<ArrayType>(T1) && T1Quals)
4370 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4371 if (isa<ArrayType>(T2) && T2Quals)
4372 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4373
4374 // C++ [dcl.init.ref]p4:
4375 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4376 // reference-related to T2 and cv1 is the same cv-qualification
4377 // as, or greater cv-qualification than, cv2. For purposes of
4378 // overload resolution, cases for which cv1 is greater
4379 // cv-qualification than cv2 are identified as
4380 // reference-compatible with added qualification (see 13.3.3.2).
4381 //
4382 // Note that we also require equivalence of Objective-C GC and address-space
4383 // qualifiers when performing these computations, so that e.g., an int in
4384 // address space 1 is not reference-compatible with an int in address
4385 // space 2.
4386 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4387 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
4388 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4389 ObjCLifetimeConversion = true;
4390
4391 T1Quals.removeObjCLifetime();
4392 T2Quals.removeObjCLifetime();
4393 }
4394
4395 // MS compiler ignores __unaligned qualifier for references; do the same.
4396 T1Quals.removeUnaligned();
4397 T2Quals.removeUnaligned();
4398
4399 if (T1Quals.compatiblyIncludes(T2Quals))
4400 return Ref_Compatible;
4401 else
4402 return Ref_Related;
4403}
4404
4405/// Look for a user-defined conversion to a value reference-compatible
4406/// with DeclType. Return true if something definite is found.
4407static bool
4408FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4409 QualType DeclType, SourceLocation DeclLoc,
4410 Expr *Init, QualType T2, bool AllowRvalues,
4411 bool AllowExplicit) {
4412 assert(T2->isRecordType() && "Can only find conversions of record types.");
4413 CXXRecordDecl *T2RecordDecl
4414 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4415
4416 OverloadCandidateSet CandidateSet(
4417 DeclLoc, OverloadCandidateSet::CSK_InitByUserDefinedConversion);
4418 const auto &Conversions = T2RecordDecl->getVisibleConversionFunctions();
4419 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
4420 NamedDecl *D = *I;
4421 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4422 if (isa<UsingShadowDecl>(D))
4423 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4424
4425 FunctionTemplateDecl *ConvTemplate
4426 = dyn_cast<FunctionTemplateDecl>(D);
4427 CXXConversionDecl *Conv;
4428 if (ConvTemplate)
4429 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4430 else
4431 Conv = cast<CXXConversionDecl>(D);
4432
4433 // If this is an explicit conversion, and we're not allowed to consider
4434 // explicit conversions, skip it.
4435 if (!AllowExplicit && Conv->isExplicit())
4436 continue;
4437
4438 if (AllowRvalues) {
4439 bool DerivedToBase = false;
4440 bool ObjCConversion = false;
4441 bool ObjCLifetimeConversion = false;
4442
4443 // If we are initializing an rvalue reference, don't permit conversion
4444 // functions that return lvalues.
4445 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4446 const ReferenceType *RefType
4447 = Conv->getConversionType()->getAs<LValueReferenceType>();
4448 if (RefType && !RefType->getPointeeType()->isFunctionType())
4449 continue;
4450 }
4451
4452 if (!ConvTemplate &&
4453 S.CompareReferenceRelationship(
4454 DeclLoc,
4455 Conv->getConversionType().getNonReferenceType()
4456 .getUnqualifiedType(),
4457 DeclType.getNonReferenceType().getUnqualifiedType(),
4458 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
4459 Sema::Ref_Incompatible)
4460 continue;
4461 } else {
4462 // If the conversion function doesn't return a reference type,
4463 // it can't be considered for this conversion. An rvalue reference
4464 // is only acceptable if its referencee is a function type.
4465
4466 const ReferenceType *RefType =
4467 Conv->getConversionType()->getAs<ReferenceType>();
4468 if (!RefType ||
4469 (!RefType->isLValueReferenceType() &&
4470 !RefType->getPointeeType()->isFunctionType()))
4471 continue;
4472 }
4473
4474 if (ConvTemplate)
4475 S.AddTemplateConversionCandidate(
4476 ConvTemplate, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4477 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4478 else
4479 S.AddConversionCandidate(
4480 Conv, I.getPair(), ActingDC, Init, DeclType, CandidateSet,
4481 /*AllowObjCConversionOnExplicit=*/false, AllowExplicit);
4482 }
4483
4484 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4485
4486 OverloadCandidateSet::iterator Best;
4487 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best)) {
4488 case OR_Success:
4489 // C++ [over.ics.ref]p1:
4490 //
4491 // [...] If the parameter binds directly to the result of
4492 // applying a conversion function to the argument
4493 // expression, the implicit conversion sequence is a
4494 // user-defined conversion sequence (13.3.3.1.2), with the
4495 // second standard conversion sequence either an identity
4496 // conversion or, if the conversion function returns an
4497 // entity of a type that is a derived class of the parameter
4498 // type, a derived-to-base Conversion.
4499 if (!Best->FinalConversion.DirectBinding)
4500 return false;
4501
4502 ICS.setUserDefined();
4503 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4504 ICS.UserDefined.After = Best->FinalConversion;
4505 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
4506 ICS.UserDefined.ConversionFunction = Best->Function;
4507 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
4508 ICS.UserDefined.EllipsisConversion = false;
4509 assert(ICS.UserDefined.After.ReferenceBinding &&
4510 ICS.UserDefined.After.DirectBinding &&
4511 "Expected a direct reference binding!");
4512 return true;
4513
4514 case OR_Ambiguous:
4515 ICS.setAmbiguous();
4516 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4517 Cand != CandidateSet.end(); ++Cand)
4518 if (Cand->Viable)
4519 ICS.Ambiguous.addConversion(Cand->FoundDecl, Cand->Function);
4520 return true;
4521
4522 case OR_No_Viable_Function:
4523 case OR_Deleted:
4524 // There was no suitable conversion, or we found a deleted
4525 // conversion; continue with other checks.
4526 return false;
4527 }
4528
4529 llvm_unreachable("Invalid OverloadResult!");
4530}
4531
4532/// Compute an implicit conversion sequence for reference
4533/// initialization.
4534static ImplicitConversionSequence
4535TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
4536 SourceLocation DeclLoc,
4537 bool SuppressUserConversions,
4538 bool AllowExplicit) {
4539 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4540
4541 // Most paths end in a failed conversion.
4542 ImplicitConversionSequence ICS;
4543 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4544
4545 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4546 QualType T2 = Init->getType();
4547
4548 // If the initializer is the address of an overloaded function, try
4549 // to resolve the overloaded function. If all goes well, T2 is the
4550 // type of the resulting function.
4551 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4552 DeclAccessPair Found;
4553 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4554 false, Found))
4555 T2 = Fn->getType();
4556 }
4557
4558 // Compute some basic properties of the types and the initializer.
4559 bool isRValRef = DeclType->isRValueReferenceType();
4560 bool DerivedToBase = false;
4561 bool ObjCConversion = false;
4562 bool ObjCLifetimeConversion = false;
4563 Expr::Classification InitCategory = Init->Classify(S.Context);
4564 Sema::ReferenceCompareResult RefRelationship
4565 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
4566 ObjCConversion, ObjCLifetimeConversion);
4567
4568
4569 // C++0x [dcl.init.ref]p5:
4570 // A reference to type "cv1 T1" is initialized by an expression
4571 // of type "cv2 T2" as follows:
4572
4573 // -- If reference is an lvalue reference and the initializer expression
4574 if (!isRValRef) {
4575 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4576 // reference-compatible with "cv2 T2," or
4577 //
4578 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4579 if (InitCategory.isLValue() && RefRelationship == Sema::Ref_Compatible) {
4580 // C++ [over.ics.ref]p1:
4581 // When a parameter of reference type binds directly (8.5.3)
4582 // to an argument expression, the implicit conversion sequence
4583 // is the identity conversion, unless the argument expression
4584 // has a type that is a derived class of the parameter type,
4585 // in which case the implicit conversion sequence is a
4586 // derived-to-base Conversion (13.3.3.1).
4587 ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
4588 ICS.Standard.First = ICK_Identity;
4589 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4590 : ObjCConversion? ICK_Compatible_Conversion
4591 : ICK_Identity;
4592 ICS.Standard.Third = ICK_Identity;
4593 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4594 ICS.Standard.setToType(0, T2);
4595 ICS.Standard.setToType(1, T1);
4596 ICS.Standard.setToType(2, T1);
4597 ICS.Standard.ReferenceBinding = true;
4598 ICS.Standard.DirectBinding = true;
4599 ICS.Standard.IsLvalueReference = !isRValRef;
4600 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4601 ICS.Standard.BindsToRvalue = false;
4602 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4603 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4604 ICS.Standard.CopyConstructor = nullptr;
4605 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4606 // FIXME: CHERI compatibility check
4607
4608 // Nothing more to do: the inaccessibility/ambiguity check for
4609 // derived-to-base conversions is suppressed when we're
4610 // computing the implicit conversion sequence (C++
4611 // [over.best.ics]p2).
4612 return ICS;
4613 }
4614
4615 // -- has a class type (i.e., T2 is a class type), where T1 is
4616 // not reference-related to T2, and can be implicitly
4617 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4618 // is reference-compatible with "cv3 T3" 92) (this
4619 // conversion is selected by enumerating the applicable
4620 // conversion functions (13.3.1.6) and choosing the best
4621 // one through overload resolution (13.3)),
4622 if (!SuppressUserConversions && T2->isRecordType() &&
4623 S.isCompleteType(DeclLoc, T2) &&
4624 RefRelationship == Sema::Ref_Incompatible) {
4625 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4626 Init, T2, /*AllowRvalues=*/false,
4627 AllowExplicit))
4628 return ICS;
4629 }
4630 }
4631
4632 // -- Otherwise, the reference shall be an lvalue reference to a
4633 // non-volatile const type (i.e., cv1 shall be const), or the reference
4634 // shall be an rvalue reference.
4635 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
4636 return ICS;
4637
4638 // -- If the initializer expression
4639 //
4640 // -- is an xvalue, class prvalue, array prvalue or function
4641 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
4642 if (RefRelationship == Sema::Ref_Compatible &&
4643 (InitCategory.isXValue() ||
4644 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4645 (InitCategory.isLValue() && T2->isFunctionType()))) {
4646 ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
4647 ICS.Standard.First = ICK_Identity;
4648 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4649 : ObjCConversion? ICK_Compatible_Conversion
4650 : ICK_Identity;
4651 ICS.Standard.Third = ICK_Identity;
4652 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4653 ICS.Standard.setToType(0, T2);
4654 ICS.Standard.setToType(1, T1);
4655 ICS.Standard.setToType(2, T1);
4656 ICS.Standard.ReferenceBinding = true;
4657 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4658 // binding unless we're binding to a class prvalue.
4659 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4660 // allow the use of rvalue references in C++98/03 for the benefit of
4661 // standard library implementors; therefore, we need the xvalue check here.
4662 ICS.Standard.DirectBinding =
4663 S.getLangOpts().CPlusPlus11 ||
4664 !(InitCategory.isPRValue() || T2->isRecordType());
4665 ICS.Standard.IsLvalueReference = !isRValRef;
4666 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4667 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
4668 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4669 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
4670 ICS.Standard.CopyConstructor = nullptr;
4671 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
4672 return ICS;
4673 }
4674
4675 // -- has a class type (i.e., T2 is a class type), where T1 is not
4676 // reference-related to T2, and can be implicitly converted to
4677 // an xvalue, class prvalue, or function lvalue of type
4678 // "cv3 T3", where "cv1 T1" is reference-compatible with
4679 // "cv3 T3",
4680 //
4681 // then the reference is bound to the value of the initializer
4682 // expression in the first case and to the result of the conversion
4683 // in the second case (or, in either case, to an appropriate base
4684 // class subobject).
4685 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4686 T2->isRecordType() && S.isCompleteType(DeclLoc, T2) &&
4687 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4688 Init, T2, /*AllowRvalues=*/true,
4689 AllowExplicit)) {
4690 // In the second case, if the reference is an rvalue reference
4691 // and the second standard conversion sequence of the
4692 // user-defined conversion sequence includes an lvalue-to-rvalue
4693 // conversion, the program is ill-formed.
4694 if (ICS.isUserDefined() && isRValRef &&
4695 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4696 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4697
4698 return ICS;
4699 }
4700
4701 // A temporary of function type cannot be created; don't even try.
4702 if (T1->isFunctionType())
4703 return ICS;
4704
4705 // -- Otherwise, a temporary of type "cv1 T1" is created and
4706 // initialized from the initializer expression using the
4707 // rules for a non-reference copy initialization (8.5). The
4708 // reference is then bound to the temporary. If T1 is
4709 // reference-related to T2, cv1 must be the same
4710 // cv-qualification as, or greater cv-qualification than,
4711 // cv2; otherwise, the program is ill-formed.
4712 if (RefRelationship == Sema::Ref_Related) {
4713 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4714 // we would be reference-compatible or reference-compatible with
4715 // added qualification. But that wasn't the case, so the reference
4716 // initialization fails.
4717 //
4718 // Note that we only want to check address spaces and cvr-qualifiers here.
4719 // ObjC GC, lifetime and unaligned qualifiers aren't important.
4720 Qualifiers T1Quals = T1.getQualifiers();
4721 Qualifiers T2Quals = T2.getQualifiers();
4722 T1Quals.removeObjCGCAttr();
4723 T1Quals.removeObjCLifetime();
4724 T2Quals.removeObjCGCAttr();
4725 T2Quals.removeObjCLifetime();
4726 // MS compiler ignores __unaligned qualifier for references; do the same.
4727 T1Quals.removeUnaligned();
4728 T2Quals.removeUnaligned();
4729 if (!T1Quals.compatiblyIncludes(T2Quals))
4730 return ICS;
4731 }
4732
4733 // If at least one of the types is a class type, the types are not
4734 // related, and we aren't allowed any user conversions, the
4735 // reference binding fails. This case is important for breaking
4736 // recursion, since TryImplicitConversion below will attempt to
4737 // create a temporary through the use of a copy constructor.
4738 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4739 (T1->isRecordType() || T2->isRecordType()))
4740 return ICS;
4741
4742 // If T1 is reference-related to T2 and the reference is an rvalue
4743 // reference, the initializer expression shall not be an lvalue.
4744 if (RefRelationship >= Sema::Ref_Related &&
4745 isRValRef && Init->Classify(S.Context).isLValue())
4746 return ICS;
4747
4748 // C++ [over.ics.ref]p2:
4749 // When a parameter of reference type is not bound directly to
4750 // an argument expression, the conversion sequence is the one
4751 // required to convert the argument expression to the
4752 // underlying type of the reference according to
4753 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4754 // to copy-initializing a temporary of the underlying type with
4755 // the argument expression. Any difference in top-level
4756 // cv-qualification is subsumed by the initialization itself
4757 // and does not constitute a conversion.
4758 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4759 /*AllowExplicit=*/false,
4760 /*InOverloadResolution=*/false,
4761 /*CStyle=*/false,
4762 /*AllowObjCWritebackConversion=*/false,
4763 /*AllowObjCConversionOnExplicit=*/false);
4764
4765 // Of course, that's still a reference binding.
4766 if (ICS.isStandard()) {
4767 ICS.Standard.ReferenceBinding = true;
4768 ICS.Standard.IsLvalueReference = !isRValRef;
4769 ICS.Standard.BindsToFunctionLvalue = false;
4770 ICS.Standard.BindsToRvalue = true;
4771 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4772 ICS.Standard.ObjCLifetimeConversionBinding = false;
4773 } else if (ICS.isUserDefined()) {
4774 const ReferenceType *LValRefType =
4775 ICS.UserDefined.ConversionFunction->getReturnType()
4776 ->getAs<LValueReferenceType>();
4777
4778 // C++ [over.ics.ref]p3:
4779 // Except for an implicit object parameter, for which see 13.3.1, a
4780 // standard conversion sequence cannot be formed if it requires [...]
4781 // binding an rvalue reference to an lvalue other than a function
4782 // lvalue.
4783 // Note that the function case is not possible here.
4784 if (DeclType->isRValueReferenceType() && LValRefType) {
4785 // FIXME: This is the wrong BadConversionSequence. The problem is binding
4786 // an rvalue reference to a (non-function) lvalue, not binding an lvalue
4787 // reference to an rvalue!
4788 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init, DeclType);
4789 return ICS;
4790 }
4791
4792 ICS.UserDefined.After.ReferenceBinding = true;
4793 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4794 ICS.UserDefined.After.BindsToFunctionLvalue = false;
4795 ICS.UserDefined.After.BindsToRvalue = !LValRefType;
4796 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4797 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
4798 }
4799
4800 return ICS;
4801}
4802
4803static ImplicitConversionSequence
4804TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4805 bool SuppressUserConversions,
4806 bool InOverloadResolution,
4807 bool AllowObjCWritebackConversion,
4808 bool AllowExplicit = false);
4809
4810/// TryListConversion - Try to copy-initialize a value of type ToType from the
4811/// initializer list From.
4812static ImplicitConversionSequence
4813TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4814 bool SuppressUserConversions,
4815 bool InOverloadResolution,
4816 bool AllowObjCWritebackConversion) {
4817 // C++11 [over.ics.list]p1:
4818 // When an argument is an initializer list, it is not an expression and
4819 // special rules apply for converting it to a parameter type.
4820
4821 ImplicitConversionSequence Result;
4822 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4823
4824 // We need a complete type for what follows. Incomplete types can never be
4825 // initialized from init lists.
4826 if (!S.isCompleteType(From->getBeginLoc(), ToType))
4827 return Result;
4828
4829 // Per DR1467:
4830 // If the parameter type is a class X and the initializer list has a single
4831 // element of type cv U, where U is X or a class derived from X, the
4832 // implicit conversion sequence is the one required to convert the element
4833 // to the parameter type.
4834 //
4835 // Otherwise, if the parameter type is a character array [... ]
4836 // and the initializer list has a single element that is an
4837 // appropriately-typed string literal (8.5.2 [dcl.init.string]), the
4838 // implicit conversion sequence is the identity conversion.
4839 if (From->getNumInits() == 1) {
4840 if (ToType->isRecordType()) {
4841 QualType InitType = From->getInit(0)->getType();
4842 if (S.Context.hasSameUnqualifiedType(InitType, ToType) ||
4843 S.IsDerivedFrom(From->getBeginLoc(), InitType, ToType))
4844 return TryCopyInitialization(S, From->getInit(0), ToType,
4845 SuppressUserConversions,
4846 InOverloadResolution,
4847 AllowObjCWritebackConversion);
4848 }
4849 // FIXME: Check the other conditions here: array of character type,
4850 // initializer is a string literal.
4851 if (ToType->isArrayType()) {
4852 InitializedEntity Entity =
4853 InitializedEntity::InitializeParameter(S.Context, ToType,
4854 /*Consumed=*/false);
4855 if (S.CanPerformCopyInitialization(Entity, From)) {
4856 Result.setAsIdentityConversion(ToType);
4857 return Result;
4858 }
4859 }
4860 }
4861
4862 // C++14 [over.ics.list]p2: Otherwise, if the parameter type [...] (below).
4863 // C++11 [over.ics.list]p2:
4864 // If the parameter type is std::initializer_list<X> or "array of X" and
4865 // all the elements can be implicitly converted to X, the implicit
4866 // conversion sequence is the worst conversion necessary to convert an
4867 // element of the list to X.
4868 //
4869 // C++14 [over.ics.list]p3:
4870 // Otherwise, if the parameter type is "array of N X", if the initializer
4871 // list has exactly N elements or if it has fewer than N elements and X is
4872 // default-constructible, and if all the elements of the initializer list
4873 // can be implicitly converted to X, the implicit conversion sequence is
4874 // the worst conversion necessary to convert an element of the list to X.
4875 //
4876 // FIXME: We're missing a lot of these checks.
4877 bool toStdInitializerList = false;
4878 QualType X;
4879 if (ToType->isArrayType())
4880 X = S.Context.getAsArrayType(ToType)->getElementType();
4881 else
4882 toStdInitializerList = S.isStdInitializerList(ToType, &X);
4883 if (!X.isNull()) {
4884 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4885 Expr *Init = From->getInit(i);
4886 ImplicitConversionSequence ICS =
4887 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4888 InOverloadResolution,
4889 AllowObjCWritebackConversion);
4890 // If a single element isn't convertible, fail.
4891 if (ICS.isBad()) {
4892 Result = ICS;
4893 break;
4894 }
4895 // Otherwise, look for the worst conversion.
4896 if (Result.isBad() || CompareImplicitConversionSequences(
4897 S, From->getBeginLoc(), ICS, Result) ==
4898 ImplicitConversionSequence::Worse)
4899 Result = ICS;
4900 }
4901
4902 // For an empty list, we won't have computed any conversion sequence.
4903 // Introduce the identity conversion sequence.
4904 if (From->getNumInits() == 0) {
4905 Result.setAsIdentityConversion(ToType);
4906 }
4907
4908 Result.setStdInitializerListElement(toStdInitializerList);
4909 return Result;
4910 }
4911
4912 // C++14 [over.ics.list]p4:
4913 // C++11 [over.ics.list]p3:
4914 // Otherwise, if the parameter is a non-aggregate class X and overload
4915 // resolution chooses a single best constructor [...] the implicit
4916 // conversion sequence is a user-defined conversion sequence. If multiple
4917 // constructors are viable but none is better than the others, the
4918 // implicit conversion sequence is a user-defined conversion sequence.
4919 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4920 // This function can deal with initializer lists.
4921 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4922 /*AllowExplicit=*/false,
4923 InOverloadResolution, /*CStyle=*/false,
4924 AllowObjCWritebackConversion,
4925 /*AllowObjCConversionOnExplicit=*/false);
4926 }
4927
4928 // C++14 [over.ics.list]p5:
4929 // C++11 [over.ics.list]p4:
4930 // Otherwise, if the parameter has an aggregate type which can be
4931 // initialized from the initializer list [...] the implicit conversion
4932 // sequence is a user-defined conversion sequence.
4933 if (ToType->isAggregateType()) {
4934 // Type is an aggregate, argument is an init list. At this point it comes
4935 // down to checking whether the initialization works.
4936 // FIXME: Find out whether this parameter is consumed or not.
4937 // FIXME: Expose SemaInit's aggregate initialization code so that we don't
4938 // need to call into the initialization code here; overload resolution
4939 // should not be doing that.
4940 InitializedEntity Entity =
4941 InitializedEntity::InitializeParameter(S.Context, ToType,
4942 /*Consumed=*/false);
4943 if (S.CanPerformCopyInitialization(Entity, From)) {
4944 Result.setUserDefined();
4945 Result.UserDefined.Before.setAsIdentityConversion();
4946 // Initializer lists don't have a type.
4947 Result.UserDefined.Before.setFromType(QualType());
4948 Result.UserDefined.Before.setAllToTypes(QualType());
4949
4950 Result.UserDefined.After.setAsIdentityConversion();
4951 Result.UserDefined.After.setFromType(ToType);
4952 Result.UserDefined.After.setAllToTypes(ToType);
4953 Result.UserDefined.ConversionFunction = nullptr;
4954 }
4955 return Result;
4956 }
4957
4958 // C++14 [over.ics.list]p6:
4959 // C++11 [over.ics.list]p5:
4960 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
4961 if (ToType->isReferenceType()) {
4962 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4963 // mention initializer lists in any way. So we go by what list-
4964 // initialization would do and try to extrapolate from that.
4965
4966 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4967
4968 // If the initializer list has a single element that is reference-related
4969 // to the parameter type, we initialize the reference from that.
4970 if (From->getNumInits() == 1) {
4971 Expr *Init = From->getInit(0);
4972
4973 QualType T2 = Init->getType();
4974
4975 // If the initializer is the address of an overloaded function, try
4976 // to resolve the overloaded function. If all goes well, T2 is the
4977 // type of the resulting function.
4978 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4979 DeclAccessPair Found;
4980 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4981 Init, ToType, false, Found))
4982 T2 = Fn->getType();
4983 }
4984
4985 // Compute some basic properties of the types and the initializer.
4986 bool dummy1 = false;
4987 bool dummy2 = false;
4988 bool dummy3 = false;
4989 Sema::ReferenceCompareResult RefRelationship =
4990 S.CompareReferenceRelationship(From->getBeginLoc(), T1, T2, dummy1,
4991 dummy2, dummy3);
4992
4993 if (RefRelationship >= Sema::Ref_Related) {
4994 return TryReferenceInit(S, Init, ToType, /*FIXME*/ From->getBeginLoc(),
4995 SuppressUserConversions,
4996 /*AllowExplicit=*/false);
4997 }
4998 }
4999
5000 // Otherwise, we bind the reference to a temporary created from the
5001 // initializer list.
5002 Result = TryListConversion(S, From, T1, SuppressUserConversions,
5003 InOverloadResolution,
5004 AllowObjCWritebackConversion);
5005 if (Result.isFailure())
5006 return Result;
5007 assert(!Result.isEllipsis() &&
5008 "Sub-initialization cannot result in ellipsis conversion.");
5009
5010 // Can we even bind to a temporary?
5011 if (ToType->isRValueReferenceType() ||
5012 (T1.isConstQualified() && !T1.isVolatileQualified())) {
5013 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
5014 Result.UserDefined.After;
5015 SCS.ReferenceBinding = true;
5016 SCS.IsLvalueReference = ToType->isLValueReferenceType();
5017 SCS.BindsToRvalue = true;
5018 SCS.BindsToFunctionLvalue = false;
5019 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
5020 SCS.ObjCLifetimeConversionBinding = false;
5021 } else
5022 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
5023 From, ToType);
5024 return Result;
5025 }
5026
5027 // C++14 [over.ics.list]p7:
5028 // C++11 [over.ics.list]p6:
5029 // Otherwise, if the parameter type is not a class:
5030 if (!ToType->isRecordType()) {
5031 // - if the initializer list has one element that is not itself an
5032 // initializer list, the implicit conversion sequence is the one
5033 // required to convert the element to the parameter type.
5034 unsigned NumInits = From->getNumInits();
5035 if (NumInits == 1 && !isa<InitListExpr>(From->getInit(0)))
5036 Result = TryCopyInitialization(S, From->getInit(0), ToType,
5037 SuppressUserConversions,
5038 InOverloadResolution,
5039 AllowObjCWritebackConversion);
5040 // - if the initializer list has no elements, the implicit conversion
5041 // sequence is the identity conversion.
5042 else if (NumInits == 0) {
5043 Result.setAsIdentityConversion(ToType);
5044 }
5045 return Result;
5046 }
5047
5048 // C++14 [over.ics.list]p8:
5049 // C++11 [over.ics.list]p7:
5050 // In all cases other than those enumerated above, no conversion is possible
5051 return Result;
5052}
5053
5054/// TryCopyInitialization - Try to copy-initialize a value of type
5055/// ToType from the expression From. Return the implicit conversion
5056/// sequence required to pass this argument, which may be a bad
5057/// conversion sequence (meaning that the argument cannot be passed to
5058/// a parameter of this type). If @p SuppressUserConversions, then we
5059/// do not permit any user-defined conversion sequences.
5060static ImplicitConversionSequence
5061TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
5062 bool SuppressUserConversions,
5063 bool InOverloadResolution,
5064 bool AllowObjCWritebackConversion,
5065 bool AllowExplicit) {
5066 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
5067 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
5068 InOverloadResolution,AllowObjCWritebackConversion);
5069
5070 if (ToType->isReferenceType())
5071 return TryReferenceInit(S, From, ToType,
5072 /*FIXME:*/ From->getBeginLoc(),
5073 SuppressUserConversions, AllowExplicit);
5074
5075 return TryImplicitConversion(S, From, ToType,
5076 SuppressUserConversions,
5077 /*AllowExplicit=*/false,
5078 InOverloadResolution,
5079 /*CStyle=*/false,
5080 AllowObjCWritebackConversion,
5081 /*AllowObjCConversionOnExplicit=*/false);
5082}
5083
5084static bool TryCopyInitialization(const CanQualType FromQTy,
5085 const CanQualType ToQTy,
5086 Sema &S,
5087 SourceLocation Loc,
5088 ExprValueKind FromVK) {
5089 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
5090 ImplicitConversionSequence ICS =
5091 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
5092
5093 return !ICS.isBad();
5094}
5095
5096/// TryObjectArgumentInitialization - Try to initialize the object
5097/// parameter of the given member function (@c Method) from the
5098/// expression @p From.
5099static ImplicitConversionSequence
5100TryObjectArgumentInitialization(Sema &S, SourceLocation Loc, QualType FromType,
5101 Expr::Classification FromClassification,
5102 CXXMethodDecl *Method,
5103 CXXRecordDecl *ActingContext) {
5104 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
5105 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
5106 // const volatile object.
5107 Qualifiers Quals;
5108 if (isa<CXXDestructorDecl>(Method)) {
5109 Quals.addConst();
5110 Quals.addVolatile();
5111 } else {
5112 Quals = Method->getMethodQualifiers();
5113 }
5114
5115 QualType ImplicitParamType = S.Context.getQualifiedType(ClassType, Quals);
5116
5117 // Set up the conversion sequence as a "bad" conversion, to allow us
5118 // to exit early.
5119 ImplicitConversionSequence ICS;
5120
5121 // We need to have an object of class type.
5122 if (const PointerType *PT = FromType->getAs<PointerType>()) {
5123 FromType = PT->getPointeeType();
5124
5125 // When we had a pointer, it's implicitly dereferenced, so we
5126 // better have an lvalue.
5127 assert(FromClassification.isLValue());
5128 }
5129
5130 assert(FromType->isRecordType());
5131
5132 // C++0x [over.match.funcs]p4:
5133 // For non-static member functions, the type of the implicit object
5134 // parameter is
5135 //
5136 // - "lvalue reference to cv X" for functions declared without a
5137 // ref-qualifier or with the & ref-qualifier
5138 // - "rvalue reference to cv X" for functions declared with the &&
5139 // ref-qualifier
5140 //
5141 // where X is the class of which the function is a member and cv is the
5142 // cv-qualification on the member function declaration.
5143 //
5144 // However, when finding an implicit conversion sequence for the argument, we
5145 // are not allowed to perform user-defined conversions
5146 // (C++ [over.match.funcs]p5). We perform a simplified version of
5147 // reference binding here, that allows class rvalues to bind to
5148 // non-constant references.
5149
5150 // First check the qualifiers.
5151 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
5152 if (ImplicitParamType.getCVRQualifiers()
5153 != FromTypeCanon.getLocalCVRQualifiers() &&
5154 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
5155 ICS.setBad(BadConversionSequence::bad_qualifiers,
5156 FromType, ImplicitParamType);
5157 return ICS;
5158 }
5159
5160 if (FromTypeCanon.getQualifiers().hasAddressSpace()) {
5161 Qualifiers QualsImplicitParamType = ImplicitParamType.getQualifiers();
5162 Qualifiers QualsFromType = FromTypeCanon.getQualifiers();
5163 if (!QualsImplicitParamType.isAddressSpaceSupersetOf(QualsFromType)) {
5164 ICS.setBad(BadConversionSequence::bad_qualifiers,
5165 FromType, ImplicitParamType);
5166 return ICS;
5167 }
5168 }
5169
5170 // Check that we have either the same type or a derived type. It
5171 // affects the conversion rank.
5172 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
5173 ImplicitConversionKind SecondKind;
5174 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
5175 SecondKind = ICK_Identity;
5176 } else if (S.IsDerivedFrom(Loc, FromType, ClassType))
5177 SecondKind = ICK_Derived_To_Base;
5178 else {
5179 ICS.setBad(BadConversionSequence::unrelated_class,
5180 FromType, ImplicitParamType);
5181 return ICS;
5182 }
5183
5184 // Check the ref-qualifier.
5185 switch (Method->getRefQualifier()) {
5186 case RQ_None:
5187 // Do nothing; we don't care about lvalueness or rvalueness.
5188 break;
5189
5190 case RQ_LValue:
5191 if (!FromClassification.isLValue() && !Quals.hasOnlyConst()) {
5192 // non-const lvalue reference cannot bind to an rvalue
5193 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
5194 ImplicitParamType);
5195 return ICS;
5196 }
5197 break;
5198
5199 case RQ_RValue:
5200 if (!FromClassification.isRValue()) {
5201 // rvalue reference cannot bind to an lvalue
5202 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
5203 ImplicitParamType);
5204 return ICS;
5205 }
5206 break;
5207 }
5208
5209 // Success. Mark this as a reference binding.
5210 // XXXAR: FIXME: DO CHERI CHECK
5211 ICS.setStandard(ImplicitConversionSequence::MemsetToZero);
5212 ICS.Standard.setAsIdentityConversion();
5213 ICS.Standard.Second = SecondKind;
5214 ICS.Standard.setFromType(FromType);
5215 ICS.Standard.setAllToTypes(ImplicitParamType);
5216 ICS.Standard.ReferenceBinding = true;
5217 ICS.Standard.DirectBinding = true;
5218 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
5219 ICS.Standard.BindsToFunctionLvalue = false;
5220 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
5221 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
5222 = (Method->getRefQualifier() == RQ_None);
5223 return ICS;
5224}
5225
5226/// PerformObjectArgumentInitialization - Perform initialization of
5227/// the implicit object parameter for the given Method with the given
5228/// expression.
5229ExprResult
5230Sema::PerformObjectArgumentInitialization(Expr *From,
5231 NestedNameSpecifier *Qualifier,
5232 NamedDecl *FoundDecl,
5233 CXXMethodDecl *Method) {
5234 QualType FromRecordType, DestType;
5235 QualType ImplicitParamRecordType =
5236 Method->getThisType()->getAs<PointerType>()->getPointeeType();
5237
5238 Expr::Classification FromClassification;
5239 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
5240 FromRecordType = PT->getPointeeType();
5241 DestType = Method->getThisType();
5242 FromClassification = Expr::Classification::makeSimpleLValue();
5243 } else {
5244 FromRecordType = From->getType();
5245 DestType = ImplicitParamRecordType;
5246 FromClassification = From->Classify(Context);
5247
5248 // When performing member access on an rvalue, materialize a temporary.
5249 if (From->isRValue()) {
5250 From = CreateMaterializeTemporaryExpr(FromRecordType, From,
5251 Method->getRefQualifier() !=
5252 RefQualifierKind::RQ_RValue);
5253 }
5254 }
5255
5256 // Note that we always use the true parent context when performing
5257 // the actual argument initialization.
5258 ImplicitConversionSequence ICS = TryObjectArgumentInitialization(
5259 *this, From->getBeginLoc(), From->getType(), FromClassification, Method,
5260 Method->getParent());
5261 if (ICS.isBad()) {
5262 switch (ICS.Bad.Kind) {
5263 case BadConversionSequence::bad_qualifiers: {
5264 Qualifiers FromQs = FromRecordType.getQualifiers();
5265 Qualifiers ToQs = DestType.getQualifiers();
5266 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5267 if (CVR) {
5268 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_cvr)
5269 << Method->getDeclName() << FromRecordType << (CVR - 1)
5270 << From->getSourceRange();
5271 Diag(Method->getLocation(), diag::note_previous_decl)
5272 << Method->getDeclName();
5273 return ExprError();
5274 }
5275 break;
5276 }
5277
5278 case BadConversionSequence::lvalue_ref_to_rvalue:
5279 case BadConversionSequence::rvalue_ref_to_lvalue: {
5280 bool IsRValueQualified =
5281 Method->getRefQualifier() == RefQualifierKind::RQ_RValue;
5282 Diag(From->getBeginLoc(), diag::err_member_function_call_bad_ref)
5283 << Method->getDeclName() << FromClassification.isRValue()
5284 << IsRValueQualified;
5285 Diag(Method->getLocation(), diag::note_previous_decl)
5286 << Method->getDeclName();
5287 return ExprError();
5288 }
5289
5290 case BadConversionSequence::no_conversion:
5291 case BadConversionSequence::unrelated_class:
5292 break;
5293 }
5294
5295 return Diag(From->getBeginLoc(), diag::err_member_function_call_bad_type)
5296 << ImplicitParamRecordType << FromRecordType
5297 << From->getSourceRange();
5298 }
5299
5300 if (ICS.Standard.Second == ICK_Derived_To_Base) {
5301 ExprResult FromRes =
5302 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
5303 if (FromRes.isInvalid())
5304 return ExprError();
5305 From = FromRes.get();
5306 }
5307
5308 if (!Context.hasSameType(From->getType(), DestType)) {
5309 CastKind CK;
5310 if (FromRecordType.getAddressSpace() != DestType.getAddressSpace())
5311 CK = CK_AddressSpaceConversion;
5312 else
5313 CK = CK_NoOp;
5314 From = ImpCastExprToType(From, DestType, CK, From->getValueKind()).get();
5315 }
5316 return From;
5317}
5318
5319/// TryContextuallyConvertToBool - Attempt to contextually convert the
5320/// expression From to bool (C++0x [conv]p3).
5321static ImplicitConversionSequence
5322TryContextuallyConvertToBool(Sema &S, Expr *From) {
5323 return TryImplicitConversion(S, From, S.Context.BoolTy,
5324 /*SuppressUserConversions=*/false,
5325 /*AllowExplicit=*/true,
5326 /*InOverloadResolution=*/false,
5327 /*CStyle=*/false,
5328 /*AllowObjCWritebackConversion=*/false,
5329 /*AllowObjCConversionOnExplicit=*/false);
5330}
5331
5332/// PerformContextuallyConvertToBool - Perform a contextual conversion
5333/// of the expression From to bool (C++0x [conv]p3).
5334ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
5335 if (checkPlaceholderForOverload(*this, From))
5336 return ExprError();
5337
5338 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
5339 if (!ICS.isBad())
5340 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
5341
5342 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
5343 return Diag(From->getBeginLoc(), diag::err_typecheck_bool_condition)
5344 << From->getType() << From->getSourceRange();
5345 return ExprError();
5346}
5347
5348/// Check that the specified conversion is permitted in a converted constant
5349/// expression, according to C++11 [expr.const]p3. Return true if the conversion
5350/// is acceptable.
5351static bool CheckConvertedConstantConversions(Sema &S,
5352 StandardConversionSequence &SCS) {
5353 // Since we know that the target type is an integral or unscoped enumeration
5354 // type, most conversion kinds are impossible. All possible First and Third
5355 // conversions are fine.
5356 switch (SCS.Second) {
5357 case ICK_Identity:
5358 case ICK_Function_Conversion:
5359 case ICK_Integral_Promotion:
5360 case ICK_Integral_Conversion: // Narrowing conversions are checked elsewhere.
5361 case ICK_Zero_Queue_Conversion:
5362 return true;
5363
5364 case ICK_Boolean_Conversion:
5365 // Conversion from an integral or unscoped enumeration type to bool is
5366 // classified as ICK_Boolean_Conversion, but it's also arguably an integral
5367 // conversion, so we allow it in a converted constant expression.
5368 //
5369 // FIXME: Per core issue 1407, we should not allow this, but that breaks
5370 // a lot of popular code. We should at least add a warning for this
5371 // (non-conforming) extension.
5372 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
5373 SCS.getToType(2)->isBooleanType();
5374
5375 case ICK_Pointer_Conversion:
5376 case ICK_Pointer_Member:
5377 // C++1z: null pointer conversions and null member pointer conversions are
5378 // only permitted if the source type is std::nullptr_t.
5379 return SCS.getFromType()->isNullPtrType();
5380
5381 case ICK_Floating_Promotion:
5382 case ICK_Complex_Promotion:
5383 case ICK_Floating_Conversion:
5384 case ICK_Complex_Conversion:
5385 case ICK_Floating_Integral:
5386 case ICK_Compatible_Conversion:
5387 case ICK_Derived_To_Base:
5388 case ICK_Vector_Conversion:
5389 case ICK_Vector_Splat:
5390 case ICK_Complex_Real:
5391 case ICK_Block_Pointer_Conversion:
5392 case ICK_TransparentUnionConversion:
5393 case ICK_Writeback_Conversion:
5394 case ICK_Zero_Event_Conversion:
5395 case ICK_C_Only_Conversion:
5396 case ICK_Incompatible_Pointer_Conversion:
5397 return false;
5398
5399 case ICK_Lvalue_To_Rvalue:
5400 case ICK_Array_To_Pointer:
5401 case ICK_Function_To_Pointer:
5402 llvm_unreachable("found a first conversion kind in Second");
5403
5404 case ICK_Qualification:
5405 llvm_unreachable("found a third conversion kind in Second");
5406
5407 case ICK_Num_Conversion_Kinds:
5408 break;
5409 }
5410
5411 llvm_unreachable("unknown conversion kind");
5412}
5413
5414/// CheckConvertedConstantExpression - Check that the expression From is a
5415/// converted constant expression of type T, perform the conversion and produce
5416/// the converted expression, per C++11 [expr.const]p3.
5417static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From,
5418 QualType T, APValue &Value,
5419 Sema::CCEKind CCE,
5420 bool RequireInt) {
5421 assert(S.getLangOpts().CPlusPlus11 &&
5422 "converted constant expression outside C++11");
5423
5424 if (checkPlaceholderForOverload(S, From))
5425 return ExprError();
5426
5427 // C++1z [expr.const]p3:
5428 // A converted constant expression of type T is an expression,
5429 // implicitly converted to type T, where the converted
5430 // expression is a constant expression and the implicit conversion
5431 // sequence contains only [... list of conversions ...].
5432 // C++1z [stmt.if]p2:
5433 // If the if statement is of the form if constexpr, the value of the
5434 // condition shall be a contextually converted constant expression of type
5435 // bool.
5436 ImplicitConversionSequence ICS =
5437 CCE == Sema::CCEK_ConstexprIf || CCE == Sema::CCEK_ExplicitBool
5438 ? TryContextuallyConvertToBool(S, From)
5439 : TryCopyInitialization(S, From, T,
5440 /*SuppressUserConversions=*/false,
5441 /*InOverloadResolution=*/false,
5442 /*AllowObjcWritebackConversion=*/false,
5443 /*AllowExplicit=*/false);
5444 StandardConversionSequence *SCS = nullptr;
5445 switch (ICS.getKind()) {
5446 case ImplicitConversionSequence::StandardConversion:
5447 SCS = &ICS.Standard;
5448 break;
5449 case ImplicitConversionSequence::UserDefinedConversion:
5450 // We are converting to a non-class type, so the Before sequence
5451 // must be trivial.
5452 SCS = &ICS.UserDefined.After;
5453 break;
5454 case ImplicitConversionSequence::AmbiguousConversion:
5455 case ImplicitConversionSequence::BadConversion:
5456 if (!S.DiagnoseMultipleUserDefinedConversion(From, T))
5457 return S.Diag(From->getBeginLoc(),
5458 diag::err_typecheck_converted_constant_expression)
5459 << From->getType() << From->getSourceRange() << T;
5460 return ExprError();
5461
5462 case ImplicitConversionSequence::EllipsisConversion:
5463 llvm_unreachable("ellipsis conversion in converted constant expression");
5464 }
5465
5466 // Check that we would only use permitted conversions.
5467 if (!CheckConvertedConstantConversions(S, *SCS)) {
5468 return S.Diag(From->getBeginLoc(),
5469 diag::err_typecheck_converted_constant_expression_disallowed)
5470 << From->getType() << From->getSourceRange() << T;
5471 }
5472 // [...] and where the reference binding (if any) binds directly.
5473 if (SCS->ReferenceBinding && !SCS->DirectBinding) {
5474 return S.Diag(From->getBeginLoc(),
5475 diag::err_typecheck_converted_constant_expression_indirect)
5476 << From->getType() << From->getSourceRange() << T;
5477 }
5478
5479 ExprResult Result =
5480 S.PerformImplicitConversion(From, T, ICS, Sema::AA_Converting);
5481 if (Result.isInvalid())
5482 return Result;
5483
5484 // Check for a narrowing implicit conversion.
5485 APValue PreNarrowingValue;
5486 QualType PreNarrowingType;
5487 switch (SCS->getNarrowingKind(S.Context, Result.get(), PreNarrowingValue,
5488 PreNarrowingType)) {
5489 case NK_Dependent_Narrowing:
5490 // Implicit conversion to a narrower type, but the expression is
5491 // value-dependent so we can't tell whether it's actually narrowing.
5492 case NK_Variable_Narrowing:
5493 // Implicit conversion to a narrower type, and the value is not a constant
5494 // expression. We'll diagnose this in a moment.
5495 case NK_Not_Narrowing:
5496 break;
5497
5498 case NK_Constant_Narrowing:
5499 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5500 << CCE << /*Constant*/ 1
5501 << PreNarrowingValue.getAsString(S.Context, PreNarrowingType) << T;
5502 break;
5503
5504 case NK_Type_Narrowing:
5505 S.Diag(From->getBeginLoc(), diag::ext_cce_narrowing)
5506 << CCE << /*Constant*/ 0 << From->getType() << T;
5507 break;
5508 }
5509
5510 if (Result.get()->isValueDependent()) {
5511 Value = APValue();
5512 return Result;
5513 }
5514
5515 // Check the expression is a constant expression.
5516 SmallVector<PartialDiagnosticAt, 8> Notes;
5517 Expr::EvalResult Eval;
5518 Eval.Diag = &Notes;
5519 Expr::ConstExprUsage Usage = CCE == Sema::CCEK_TemplateArg
5520 ? Expr::EvaluateForMangling
5521 : Expr::EvaluateForCodeGen;
5522
5523 if (!Result.get()->EvaluateAsConstantExpr(Eval, Usage, S.Context) ||
5524 (RequireInt && !Eval.Val.isInt())) {
5525 // The expression can't be folded, so we can't keep it at this position in
5526 // the AST.
5527 Result = ExprError();
5528 } else {
5529 Value = Eval.Val;
5530
5531 if (Notes.empty()) {
5532 // It's a constant expression.
5533 return ConstantExpr::Create(S.Context, Result.get());
5534 }
5535 }
5536
5537 // It's not a constant expression. Produce an appropriate diagnostic.
5538 if (Notes.size() == 1 &&
5539 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5540 S.Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5541 else {
5542 S.Diag(From->getBeginLoc(), diag::err_expr_not_cce)
5543 << CCE << From->getSourceRange();
5544 for (unsigned I = 0; I < Notes.size(); ++I)
5545 S.Diag(Notes[I].first, Notes[I].second);
5546 }
5547 return ExprError();
5548}
5549
5550ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5551 APValue &Value, CCEKind CCE) {
5552 return ::CheckConvertedConstantExpression(*this, From, T, Value, CCE, false);
5553}
5554
5555ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
5556 llvm::APSInt &Value,
5557 CCEKind CCE) {
5558 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
5559
5560 APValue V;
5561 auto R = ::CheckConvertedConstantExpression(*this, From, T, V, CCE, true);
5562 if (!R.isInvalid() && !R.get()->isValueDependent())
5563 Value = V.getInt();
5564 return R;
5565}
5566
5567
5568/// dropPointerConversions - If the given standard conversion sequence
5569/// involves any pointer conversions, remove them. This may change
5570/// the result type of the conversion sequence.
5571static void dropPointerConversion(StandardConversionSequence &SCS) {
5572 if (SCS.Second == ICK_Pointer_Conversion) {
5573 SCS.Second = ICK_Identity;
5574 SCS.Third = ICK_Identity;
5575 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5576 }
5577}
5578
5579/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5580/// convert the expression From to an Objective-C pointer type.
5581static ImplicitConversionSequence
5582TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5583 // Do an implicit conversion to 'id'.
5584 QualType Ty = S.Context.getObjCIdType();
5585 ImplicitConversionSequence ICS
5586 = TryImplicitConversion(S, From, Ty,
5587 // FIXME: Are these flags correct?
5588 /*SuppressUserConversions=*/false,
5589 /*AllowExplicit=*/true,
5590 /*InOverloadResolution=*/false,
5591 /*CStyle=*/false,
5592 /*AllowObjCWritebackConversion=*/false,
5593 /*AllowObjCConversionOnExplicit=*/true);
5594
5595 // Strip off any final conversions to 'id'.
5596 switch (ICS.getKind()) {
5597 case ImplicitConversionSequence::BadConversion:
5598 case ImplicitConversionSequence::AmbiguousConversion:
5599 case ImplicitConversionSequence::EllipsisConversion:
5600 break;
5601
5602 case ImplicitConversionSequence::UserDefinedConversion:
5603 dropPointerConversion(ICS.UserDefined.After);
5604 break;
5605
5606 case ImplicitConversionSequence::StandardConversion:
5607 dropPointerConversion(ICS.Standard);
5608 break;
5609 }
5610
5611 return ICS;
5612}
5613
5614/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5615/// conversion of the expression From to an Objective-C pointer type.
5616/// Returns a valid but null ExprResult if no conversion sequence exists.
5617ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
5618 if (checkPlaceholderForOverload(*this, From))
5619 return ExprError();
5620
5621 QualType Ty = Context.getObjCIdType();
5622 ImplicitConversionSequence ICS =
5623 TryContextuallyConvertToObjCPointer(*this, From);
5624 if (!ICS.isBad())
5625 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
5626 return ExprResult();
5627}
5628
5629/// Determine whether the provided type is an integral type, or an enumeration
5630/// type of a permitted flavor.
5631bool Sema::ICEConvertDiagnoser::match(QualType T) {
5632 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5633 : T->isIntegralOrUnscopedEnumerationType();
5634}
5635
5636static ExprResult
5637diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5638 Sema::ContextualImplicitConverter &Converter,
5639 QualType T, UnresolvedSetImpl &ViableConversions) {
5640
5641 if (Converter.Suppress)
5642 return ExprError();
5643
5644 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5645 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5646 CXXConversionDecl *Conv =
5647 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5648 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5649 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5650 }
5651 return From;
5652}
5653
5654static bool
5655diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5656 Sema::ContextualImplicitConverter &Converter,
5657 QualType T, bool HadMultipleCandidates,
5658 UnresolvedSetImpl &ExplicitConversions) {
5659 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5660 DeclAccessPair Found = ExplicitConversions[0];
5661 CXXConversionDecl *Conversion =
5662 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5663
5664 // The user probably meant to invoke the given explicit
5665 // conversion; use it.
5666 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5667 std::string TypeStr;
5668 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5669
5670 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5671 << FixItHint::CreateInsertion(From->getBeginLoc(),
5672 "static_cast<" + TypeStr + ">(")
5673 << FixItHint::CreateInsertion(
5674 SemaRef.getLocForEndOfToken(From->getEndLoc()), ")");
5675 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5676
5677 // If we aren't in a SFINAE context, build a call to the
5678 // explicit conversion function.
5679 if (SemaRef.isSFINAEContext())
5680 return true;
5681
5682 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5683 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5684 HadMultipleCandidates);
5685 if (Result.isInvalid())
5686 return true;
5687 // Record usage of conversion in an implicit cast.
5688 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5689 CK_UserDefinedConversion, Result.get(),
5690 nullptr, Result.get()->getValueKind());
5691 }
5692 return false;
5693}
5694
5695static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5696 Sema::ContextualImplicitConverter &Converter,
5697 QualType T, bool HadMultipleCandidates,
5698 DeclAccessPair &Found) {
5699 CXXConversionDecl *Conversion =
5700 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5701 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, nullptr, Found);
5702
5703 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5704 if (!Converter.SuppressConversion) {
5705 if (SemaRef.isSFINAEContext())
5706 return true;
5707
5708 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5709 << From->getSourceRange();
5710 }
5711
5712 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5713 HadMultipleCandidates);
5714 if (Result.isInvalid())
5715 return true;
5716 // Record usage of conversion in an implicit cast.
5717 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5718 CK_UserDefinedConversion, Result.get(),
5719 nullptr, Result.get()->getValueKind());
5720 return false;
5721}
5722
5723static ExprResult finishContextualImplicitConversion(
5724 Sema &SemaRef, SourceLocation Loc, Expr *From,
5725 Sema::ContextualImplicitConverter &Converter) {
5726 if (!Converter.match(From->getType()) && !Converter.Suppress)
5727 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5728 << From->getSourceRange();
5729
5730 return SemaRef.DefaultLvalueConversion(From);
5731}
5732
5733static void
5734collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5735 UnresolvedSetImpl &ViableConversions,
5736 OverloadCandidateSet &CandidateSet) {
5737 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5738 DeclAccessPair FoundDecl = ViableConversions[I];
5739 NamedDecl *D = FoundDecl.getDecl();
5740 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5741 if (isa<UsingShadowDecl>(D))
5742 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5743
5744 CXXConversionDecl *Conv;
5745 FunctionTemplateDecl *ConvTemplate;
5746 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5747 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5748 else
5749 Conv = cast<CXXConversionDecl>(D);
5750
5751 if (ConvTemplate)
5752 SemaRef.AddTemplateConversionCandidate(
5753 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5754 /*AllowObjCConversionOnExplicit=*/false, /*AllowExplicit*/ true);
5755 else
5756 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5757 ToType, CandidateSet,
5758 /*AllowObjCConversionOnExplicit=*/false,
5759 /*AllowExplicit*/ true);
5760 }
5761}
5762
5763/// Attempt to convert the given expression to a type which is accepted
5764/// by the given converter.
5765///
5766/// This routine will attempt to convert an expression of class type to a
5767/// type accepted by the specified converter. In C++11 and before, the class
5768/// must have a single non-explicit conversion function converting to a matching
5769/// type. In C++1y, there can be multiple such conversion functions, but only
5770/// one target type.
5771///
5772/// \param Loc The source location of the construct that requires the
5773/// conversion.
5774///
5775/// \param From The expression we're converting from.
5776///
5777/// \param Converter Used to control and diagnose the conversion process.
5778///
5779/// \returns The expression, converted to an integral or enumeration type if
5780/// successful.
5781ExprResult Sema::PerformContextualImplicitConversion(
5782 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
5783 // We can't perform any more checking for type-dependent expressions.
5784 if (From->isTypeDependent())
5785 return From;
5786
5787 // Process placeholders immediately.
5788 if (From->hasPlaceholderType()) {
5789 ExprResult result = CheckPlaceholderExpr(From);
5790 if (result.isInvalid())
5791 return result;
5792 From = result.get();
5793 }
5794
5795 // If the expression already has a matching type, we're golden.
5796 QualType T = From->getType();
5797 if (Converter.match(T))
5798 return DefaultLvalueConversion(From);
5799
5800 // FIXME: Check for missing '()' if T is a function type?
5801
5802 // We can only perform contextual implicit conversions on objects of class
5803 // type.
5804 const RecordType *RecordTy = T->getAs<RecordType>();
5805 if (!RecordTy || !getLangOpts().CPlusPlus) {
5806 if (!Converter.Suppress)
5807 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
5808 return From;
5809 }
5810
5811 // We must have a complete class type.
5812 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
5813 ContextualImplicitConverter &Converter;
5814 Expr *From;
5815
5816 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5817 : Converter(Converter), From(From) {}
5818
5819 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5820 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
5821 }
5822 } IncompleteDiagnoser(Converter, From);
5823
5824 if (Converter.Suppress ? !isCompleteType(Loc, T)
5825 : RequireCompleteType(Loc, T, IncompleteDiagnoser))
5826 return From;
5827
5828 // Look for a conversion to an integral or enumeration type.
5829 UnresolvedSet<4>
5830 ViableConversions; // These are *potentially* viable in C++1y.
5831 UnresolvedSet<4> ExplicitConversions;
5832 const auto &Conversions =
5833 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
5834
5835 bool HadMultipleCandidates =
5836 (std::distance(Conversions.begin(), Conversions.end()) > 1);
5837
5838 // To check that there is only one target type, in C++1y:
5839 QualType ToType;
5840 bool HasUniqueTargetType = true;
5841
5842 // Collect explicit or viable (potentially in C++1y) conversions.
5843 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
5844 NamedDecl *D = (*I)->getUnderlyingDecl();
5845 CXXConversionDecl *Conversion;
5846 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5847 if (ConvTemplate) {
5848 if (getLangOpts().CPlusPlus14)
5849 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5850 else
5851 continue; // C++11 does not consider conversion operator templates(?).
5852 } else
5853 Conversion = cast<CXXConversionDecl>(D);
5854
5855 assert((!ConvTemplate || getLangOpts().CPlusPlus14) &&
5856 "Conversion operator templates are considered potentially "
5857 "viable in C++1y");
5858
5859 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5860 if (Converter.match(CurToType) || ConvTemplate) {
5861
5862 if (Conversion->isExplicit()) {
5863 // FIXME: For C++1y, do we need this restriction?
5864 // cf. diagnoseNoViableConversion()
5865 if (!ConvTemplate)
5866 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5867 } else {
5868 if (!ConvTemplate && getLangOpts().CPlusPlus14) {
5869 if (ToType.isNull())
5870 ToType = CurToType.getUnqualifiedType();
5871 else if (HasUniqueTargetType &&
5872 (CurToType.getUnqualifiedType() != ToType))
5873 HasUniqueTargetType = false;
5874 }
5875 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5876 }
5877 }
5878 }
5879
5880 if (getLangOpts().CPlusPlus14) {
5881 // C++1y [conv]p6:
5882 // ... An expression e of class type E appearing in such a context
5883 // is said to be contextually implicitly converted to a specified
5884 // type T and is well-formed if and only if e can be implicitly
5885 // converted to a type T that is determined as follows: E is searched
5886 // for conversion functions whose return type is cv T or reference to
5887 // cv T such that T is allowed by the context. There shall be
5888 // exactly one such T.
5889
5890 // If no unique T is found:
5891 if (ToType.isNull()) {
5892 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5893 HadMultipleCandidates,
5894 ExplicitConversions))
5895 return ExprError();
5896 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5897 }
5898
5899 // If more than one unique Ts are found:
5900 if (!HasUniqueTargetType)
5901 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5902 ViableConversions);
5903
5904 // If one unique T is found:
5905 // First, build a candidate set from the previously recorded
5906 // potentially viable conversions.
5907 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Normal);
5908 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5909 CandidateSet);
5910
5911 // Then, perform overload resolution over the candidate set.
5912 OverloadCandidateSet::iterator Best;
5913 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5914 case OR_Success: {
5915 // Apply this conversion.
5916 DeclAccessPair Found =
5917 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5918 if (recordConversion(*this, Loc, From, Converter, T,
5919 HadMultipleCandidates, Found))
5920 return ExprError();
5921 break;
5922 }
5923 case OR_Ambiguous:
5924 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5925 ViableConversions);
5926 case OR_No_Viable_Function:
5927 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5928 HadMultipleCandidates,
5929 ExplicitConversions))
5930 return ExprError();
5931 LLVM_FALLTHROUGH;
5932 case OR_Deleted:
5933 // We'll complain below about a non-integral condition type.
5934 break;
5935 }
5936 } else {
5937 switch (ViableConversions.size()) {
5938 case 0: {
5939 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5940 HadMultipleCandidates,
5941 ExplicitConversions))
5942 return ExprError();
5943
5944 // We'll complain below about a non-integral condition type.
5945 break;
5946 }
5947 case 1: {
5948 // Apply this conversion.
5949 DeclAccessPair Found = ViableConversions[0];
5950 if (recordConversion(*this, Loc, From, Converter, T,
5951 HadMultipleCandidates, Found))
5952 return ExprError();
5953 break;
5954 }
5955 default:
5956 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5957 ViableConversions);
5958 }
5959 }
5960
5961 return finishContextualImplicitConversion(*this, Loc, From, Converter);
5962}
5963
5964/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
5965/// an acceptable non-member overloaded operator for a call whose
5966/// arguments have types T1 (and, if non-empty, T2). This routine
5967/// implements the check in C++ [over.match.oper]p3b2 concerning
5968/// enumeration types.
5969static bool IsAcceptableNonMemberOperatorCandidate(ASTContext &Context,
5970 FunctionDecl *Fn,
5971 ArrayRef<Expr *> Args) {
5972 QualType T1 = Args[0]->getType();
5973 QualType T2 = Args.size() > 1 ? Args[1]->getType() : QualType();
5974
5975 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
5976 return true;
5977
5978 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
5979 return true;
5980
5981 const FunctionProtoType *Proto = Fn->getType()->getAs<FunctionProtoType>();
5982 if (Proto->getNumParams() < 1)
5983 return false;
5984
5985 if (T1->isEnumeralType()) {
5986 QualType ArgType = Proto->getParamType(0).getNonReferenceType();
5987 if (Context.hasSameUnqualifiedType(T1, ArgType))
5988 return true;
5989 }
5990
5991 if (Proto->getNumParams() < 2)
5992 return false;
5993
5994 if (!T2.isNull() && T2->isEnumeralType()) {
5995 QualType ArgType = Proto->getParamType(1).getNonReferenceType();
5996 if (Context.hasSameUnqualifiedType(T2, ArgType))
5997 return true;
5998 }
5999
6000 return false;
6001}
6002
6003/// AddOverloadCandidate - Adds the given function to the set of
6004/// candidate functions, using the given function call arguments. If
6005/// @p SuppressUserConversions, then don't allow user-defined
6006/// conversions via constructors or conversion operators.
6007///
6008/// \param PartialOverloading true if we are performing "partial" overloading
6009/// based on an incomplete set of function arguments. This feature is used by
6010/// code completion.
6011void Sema::AddOverloadCandidate(
6012 FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args,
6013 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6014 bool PartialOverloading, bool AllowExplicit, bool AllowExplicitConversions,
6015 ADLCallKind IsADLCandidate, ConversionSequenceList EarlyConversions) {
6016 const FunctionProtoType *Proto
6017 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
6018 assert(Proto && "Functions without a prototype cannot be overloaded");
6019 assert(!Function->getDescribedFunctionTemplate() &&
6020 "Use AddTemplateOverloadCandidate for function templates");
6021
6022 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
6023 if (!isa<CXXConstructorDecl>(Method)) {
6024 // If we get here, it's because we're calling a member function
6025 // that is named without a member access expression (e.g.,
6026 // "this->f") that was either written explicitly or created
6027 // implicitly. This can happen with a qualified call to a member
6028 // function, e.g., X::f(). We use an empty type for the implied
6029 // object argument (C++ [over.call.func]p3), and the acting context
6030 // is irrelevant.
6031 AddMethodCandidate(Method, FoundDecl, Method->getParent(), QualType(),
6032 Expr::Classification::makeSimpleLValue(), Args,
6033 CandidateSet, SuppressUserConversions,
6034 PartialOverloading, EarlyConversions);
6035 return;
6036 }
6037 // We treat a constructor like a non-member function, since its object
6038 // argument doesn't participate in overload resolution.
6039 }
6040
6041 if (!CandidateSet.isNewCandidate(Function))
6042 return;
6043
6044 // C++ [over.match.oper]p3:
6045 // if no operand has a class type, only those non-member functions in the
6046 // lookup set that have a first parameter of type T1 or "reference to
6047 // (possibly cv-qualified) T1", when T1 is an enumeration type, or (if there
6048 // is a right operand) a second parameter of type T2 or "reference to
6049 // (possibly cv-qualified) T2", when T2 is an enumeration type, are
6050 // candidate functions.
6051 if (CandidateSet.getKind() == OverloadCandidateSet::CSK_Operator &&
6052 !IsAcceptableNonMemberOperatorCandidate(Context, Function, Args))
6053 return;
6054
6055 // C++11 [class.copy]p11: [DR1402]
6056 // A defaulted move constructor that is defined as deleted is ignored by
6057 // overload resolution.
6058 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
6059 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
6060 Constructor->isMoveConstructor())
6061 return;
6062
6063 // Overload resolution is always an unevaluated context.
6064 EnterExpressionEvaluationContext Unevaluated(
6065 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6066
6067 // Add this candidate
6068 OverloadCandidate &Candidate =
6069 CandidateSet.addCandidate(Args.size(), EarlyConversions);
6070 Candidate.FoundDecl = FoundDecl;
6071 Candidate.Function = Function;
6072 Candidate.Viable = true;
6073 Candidate.IsSurrogate = false;
6074 Candidate.IsADLCandidate = IsADLCandidate;
6075 Candidate.IgnoreObjectArgument = false;
6076 Candidate.ExplicitCallArguments = Args.size();
6077
6078 if (Function->isMultiVersion() && Function->hasAttr<TargetAttr>() &&
6079 !Function->getAttr<TargetAttr>()->isDefaultVersion()) {
6080 Candidate.Viable = false;
6081 Candidate.FailureKind = ovl_non_default_multiversion_function;
6082 return;
6083 }
6084
6085 if (Constructor) {
6086 // C++ [class.copy]p3:
6087 // A member function template is never instantiated to perform the copy
6088 // of a class object to an object of its class type.
6089 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
6090 if (Args.size() == 1 && Constructor->isSpecializationCopyingObject() &&
6091 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
6092 IsDerivedFrom(Args[0]->getBeginLoc(), Args[0]->getType(),
6093 ClassType))) {
6094 Candidate.Viable = false;
6095 Candidate.FailureKind = ovl_fail_illegal_constructor;
6096 return;
6097 }
6098
6099 // C++ [over.match.funcs]p8: (proposed DR resolution)
6100 // A constructor inherited from class type C that has a first parameter
6101 // of type "reference to P" (including such a constructor instantiated
6102 // from a template) is excluded from the set of candidate functions when
6103 // constructing an object of type cv D if the argument list has exactly
6104 // one argument and D is reference-related to P and P is reference-related
6105 // to C.
6106 auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl.getDecl());
6107 if (Shadow && Args.size() == 1 && Constructor->getNumParams() >= 1 &&
6108 Constructor->getParamDecl(0)->getType()->isReferenceType()) {
6109 QualType P = Constructor->getParamDecl(0)->getType()->getPointeeType();
6110 QualType C = Context.getRecordType(Constructor->getParent());
6111 QualType D = Context.getRecordType(Shadow->getParent());
6112 SourceLocation Loc = Args.front()->getExprLoc();
6113 if ((Context.hasSameUnqualifiedType(P, C) || IsDerivedFrom(Loc, P, C)) &&
6114 (Context.hasSameUnqualifiedType(D, P) || IsDerivedFrom(Loc, D, P))) {
6115 Candidate.Viable = false;
6116 Candidate.FailureKind = ovl_fail_inhctor_slice;
6117 return;
6118 }
6119 }
6120 }
6121
6122 unsigned NumParams = Proto->getNumParams();
6123
6124 // (C++ 13.3.2p2): A candidate function having fewer than m
6125 // parameters is viable only if it has an ellipsis in its parameter
6126 // list (8.3.5).
6127 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6128 !Proto->isVariadic()) {
6129 Candidate.Viable = false;
6130 Candidate.FailureKind = ovl_fail_too_many_arguments;
6131 return;
6132 }
6133
6134 // (C++ 13.3.2p2): A candidate function having more than m parameters
6135 // is viable only if the (m+1)st parameter has a default argument
6136 // (8.3.6). For the purposes of overload resolution, the
6137 // parameter list is truncated on the right, so that there are
6138 // exactly m parameters.
6139 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
6140 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6141 // Not enough arguments.
6142 Candidate.Viable = false;
6143 Candidate.FailureKind = ovl_fail_too_few_arguments;
6144 return;
6145 }
6146
6147 // (CUDA B.1): Check for invalid calls between targets.
6148 if (getLangOpts().CUDA)
6149 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6150 // Skip the check for callers that are implicit members, because in this
6151 // case we may not yet know what the member's target is; the target is
6152 // inferred for the member automatically, based on the bases and fields of
6153 // the class.
6154 if (!Caller->isImplicit() && !IsAllowedCUDACall(Caller, Function)) {
6155 Candidate.Viable = false;
6156 Candidate.FailureKind = ovl_fail_bad_target;
6157 return;
6158 }
6159
6160 // Determine the implicit conversion sequences for each of the
6161 // arguments.
6162 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6163 if (Candidate.Conversions[ArgIdx].isInitialized()) {
6164 // We already formed a conversion sequence for this parameter during
6165 // template argument deduction.
6166 } else if (ArgIdx < NumParams) {
6167 // (C++ 13.3.2p3): for F to be a viable function, there shall
6168 // exist for each argument an implicit conversion sequence
6169 // (13.3.3.1) that converts that argument to the corresponding
6170 // parameter of F.
6171 QualType ParamType = Proto->getParamType(ArgIdx);
6172 Candidate.Conversions[ArgIdx] = TryCopyInitialization(
6173 *this, Args[ArgIdx], ParamType, SuppressUserConversions,
6174 /*InOverloadResolution=*/true,
6175 /*AllowObjCWritebackConversion=*/
6176 getLangOpts().ObjCAutoRefCount, AllowExplicitConversions);
6177 if (Candidate.Conversions[ArgIdx].isBad()) {
6178 Candidate.Viable = false;
6179 Candidate.FailureKind = ovl_fail_bad_conversion;
6180 return;
6181 }
6182 } else {
6183 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6184 // argument for which there is no corresponding parameter is
6185 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
6186 Candidate.Conversions[ArgIdx].setEllipsis();
6187 }
6188 }
6189
6190 if (!AllowExplicit) {
6191 ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(Function);
6192 if (ES.getKind() != ExplicitSpecKind::ResolvedFalse) {
6193 Candidate.Viable = false;
6194 Candidate.FailureKind = ovl_fail_explicit_resolved;
6195 return;
6196 }
6197 }
6198
6199 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
6200 Candidate.Viable = false;
6201 Candidate.FailureKind = ovl_fail_enable_if;
6202 Candidate.DeductionFailure.Data = FailedAttr;
6203 return;
6204 }
6205
6206 if (LangOpts.OpenCL && isOpenCLDisabledDecl(Function)) {
6207 Candidate.Viable = false;
6208 Candidate.FailureKind = ovl_fail_ext_disabled;
6209 return;
6210 }
6211}
6212
6213ObjCMethodDecl *
6214Sema::SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance,
6215 SmallVectorImpl<ObjCMethodDecl *> &Methods) {
6216 if (Methods.size() <= 1)
6217 return nullptr;
6218
6219 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6220 bool Match = true;
6221 ObjCMethodDecl *Method = Methods[b];
6222 unsigned NumNamedArgs = Sel.getNumArgs();
6223 // Method might have more arguments than selector indicates. This is due
6224 // to addition of c-style arguments in method.
6225 if (Method->param_size() > NumNamedArgs)
6226 NumNamedArgs = Method->param_size();
6227 if (Args.size() < NumNamedArgs)
6228 continue;
6229
6230 for (unsigned i = 0; i < NumNamedArgs; i++) {
6231 // We can't do any type-checking on a type-dependent argument.
6232 if (Args[i]->isTypeDependent()) {
6233 Match = false;
6234 break;
6235 }
6236
6237 ParmVarDecl *param = Method->parameters()[i];
6238 Expr *argExpr = Args[i];
6239 assert(argExpr && "SelectBestMethod(): missing expression");
6240
6241 // Strip the unbridged-cast placeholder expression off unless it's
6242 // a consumed argument.
6243 if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) &&
6244 !param->hasAttr<CFConsumedAttr>())
6245 argExpr = stripARCUnbridgedCast(argExpr);
6246
6247 // If the parameter is __unknown_anytype, move on to the next method.
6248 if (param->getType() == Context.UnknownAnyTy) {
6249 Match = false;
6250 break;
6251 }
6252
6253 ImplicitConversionSequence ConversionState
6254 = TryCopyInitialization(*this, argExpr, param->getType(),
6255 /*SuppressUserConversions*/false,
6256 /*InOverloadResolution=*/true,
6257 /*AllowObjCWritebackConversion=*/
6258 getLangOpts().ObjCAutoRefCount,
6259 /*AllowExplicit*/false);
6260 // This function looks for a reasonably-exact match, so we consider
6261 // incompatible pointer conversions to be a failure here.
6262 if (ConversionState.isBad() ||
6263 (ConversionState.isStandard() &&
6264 ConversionState.Standard.Second ==
6265 ICK_Incompatible_Pointer_Conversion)) {
6266 Match = false;
6267 break;
6268 }
6269 }
6270 // Promote additional arguments to variadic methods.
6271 if (Match && Method->isVariadic()) {
6272 for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) {
6273 if (Args[i]->isTypeDependent()) {
6274 Match = false;
6275 break;
6276 }
6277 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
6278 nullptr);
6279 if (Arg.isInvalid()) {
6280 Match = false;
6281 break;
6282 }
6283 }
6284 } else {
6285 // Check for extra arguments to non-variadic methods.
6286 if (Args.size() != NumNamedArgs)
6287 Match = false;
6288 else if (Match && NumNamedArgs == 0 && Methods.size() > 1) {
6289 // Special case when selectors have no argument. In this case, select
6290 // one with the most general result type of 'id'.
6291 for (unsigned b = 0, e = Methods.size(); b < e; b++) {
6292 QualType ReturnT = Methods[b]->getReturnType();
6293 if (ReturnT->isObjCIdType())
6294 return Methods[b];
6295 }
6296 }
6297 }
6298
6299 if (Match)
6300 return Method;
6301 }
6302 return nullptr;
6303}
6304
6305static bool
6306convertArgsForAvailabilityChecks(Sema &S, FunctionDecl *Function, Expr *ThisArg,
6307 ArrayRef<Expr *> Args, Sema::SFINAETrap &Trap,
6308 bool MissingImplicitThis, Expr *&ConvertedThis,
6309 SmallVectorImpl<Expr *> &ConvertedArgs) {
6310 if (ThisArg) {
6311 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
6312 assert(!isa<CXXConstructorDecl>(Method) &&
6313 "Shouldn't have `this` for ctors!");
6314 assert(!Method->isStatic() && "Shouldn't have `this` for static methods!");
6315 ExprResult R = S.PerformObjectArgumentInitialization(
6316 ThisArg, /*Qualifier=*/nullptr, Method, Method);
6317 if (R.isInvalid())
6318 return false;
6319 ConvertedThis = R.get();
6320 } else {
6321 if (auto *MD = dyn_cast<CXXMethodDecl>(Function)) {
6322 (void)MD;
6323 assert((MissingImplicitThis || MD->isStatic() ||
6324 isa<CXXConstructorDecl>(MD)) &&
6325 "Expected `this` for non-ctor instance methods");
6326 }
6327 ConvertedThis = nullptr;
6328 }
6329
6330 // Ignore any variadic arguments. Converting them is pointless, since the
6331 // user can't refer to them in the function condition.
6332 unsigned ArgSizeNoVarargs = std::min(Function->param_size(), Args.size());
6333
6334 // Convert the arguments.
6335 for (unsigned I = 0; I != ArgSizeNoVarargs; ++I) {
6336 ExprResult R;
6337 R = S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6338 S.Context, Function->getParamDecl(I)),
6339 SourceLocation(), Args[I]);
6340
6341 if (R.isInvalid())
6342 return false;
6343
6344 ConvertedArgs.push_back(R.get());
6345 }
6346
6347 if (Trap.hasErrorOccurred())
6348 return false;
6349
6350 // Push default arguments if needed.
6351 if (!Function->isVariadic() && Args.size() < Function->getNumParams()) {
6352 for (unsigned i = Args.size(), e = Function->getNumParams(); i != e; ++i) {
6353 ParmVarDecl *P = Function->getParamDecl(i);
6354 Expr *DefArg = P->hasUninstantiatedDefaultArg()
6355 ? P->getUninstantiatedDefaultArg()
6356 : P->getDefaultArg();
6357 // This can only happen in code completion, i.e. when PartialOverloading
6358 // is true.
6359 if (!DefArg)
6360 return false;
6361 ExprResult R =
6362 S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
6363 S.Context, Function->getParamDecl(i)),
6364 SourceLocation(), DefArg);
6365 if (R.isInvalid())
6366 return false;
6367 ConvertedArgs.push_back(R.get());
6368 }
6369
6370 if (Trap.hasErrorOccurred())
6371 return false;
6372 }
6373 return true;
6374}
6375
6376EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
6377 bool MissingImplicitThis) {
6378 auto EnableIfAttrs = Function->specific_attrs<EnableIfAttr>();
6379 if (EnableIfAttrs.begin() == EnableIfAttrs.end())
6380 return nullptr;
6381
6382 SFINAETrap Trap(*this);
6383 SmallVector<Expr *, 16> ConvertedArgs;
6384 // FIXME: We should look into making enable_if late-parsed.
6385 Expr *DiscardedThis;
6386 if (!convertArgsForAvailabilityChecks(
6387 *this, Function, /*ThisArg=*/nullptr, Args, Trap,
6388 /*MissingImplicitThis=*/true, DiscardedThis, ConvertedArgs))
6389 return *EnableIfAttrs.begin();
6390
6391 for (auto *EIA : EnableIfAttrs) {
6392 APValue Result;
6393 // FIXME: This doesn't consider value-dependent cases, because doing so is
6394 // very difficult. Ideally, we should handle them more gracefully.
6395 if (EIA->getCond()->isValueDependent() ||
6396 !EIA->getCond()->EvaluateWithSubstitution(
6397 Result, Context, Function, llvm::makeArrayRef(ConvertedArgs)))
6398 return EIA;
6399
6400 if (!Result.isInt() || !Result.getInt().getBoolValue())
6401 return EIA;
6402 }
6403 return nullptr;
6404}
6405
6406template <typename CheckFn>
6407static bool diagnoseDiagnoseIfAttrsWith(Sema &S, const NamedDecl *ND,
6408 bool ArgDependent, SourceLocation Loc,
6409 CheckFn &&IsSuccessful) {
6410 SmallVector<const DiagnoseIfAttr *, 8> Attrs;
6411 for (const auto *DIA : ND->specific_attrs<DiagnoseIfAttr>()) {
6412 if (ArgDependent == DIA->getArgDependent())
6413 Attrs.push_back(DIA);
6414 }
6415
6416 // Common case: No diagnose_if attributes, so we can quit early.
6417 if (Attrs.empty())
6418 return false;
6419
6420 auto WarningBegin = std::stable_partition(
6421 Attrs.begin(), Attrs.end(),
6422 [](const DiagnoseIfAttr *DIA) { return DIA->isError(); });
6423
6424 // Note that diagnose_if attributes are late-parsed, so they appear in the
6425 // correct order (unlike enable_if attributes).
6426 auto ErrAttr = llvm::find_if(llvm::make_range(Attrs.begin(), WarningBegin),
6427 IsSuccessful);
6428 if (ErrAttr != WarningBegin) {
6429 const DiagnoseIfAttr *DIA = *ErrAttr;
6430 S.Diag(Loc, diag::err_diagnose_if_succeeded) << DIA->getMessage();
6431 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6432 << DIA->getParent() << DIA->getCond()->getSourceRange();
6433 return true;
6434 }
6435
6436 for (const auto *DIA : llvm::make_range(WarningBegin, Attrs.end()))
6437 if (IsSuccessful(DIA)) {
6438 S.Diag(Loc, diag::warn_diagnose_if_succeeded) << DIA->getMessage();
6439 S.Diag(DIA->getLocation(), diag::note_from_diagnose_if)
6440 << DIA->getParent() << DIA->getCond()->getSourceRange();
6441 }
6442
6443 return false;
6444}
6445
6446bool Sema::diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function,
6447 const Expr *ThisArg,
6448 ArrayRef<const Expr *> Args,
6449 SourceLocation Loc) {
6450 return diagnoseDiagnoseIfAttrsWith(
6451 *this, Function, /*ArgDependent=*/true, Loc,
6452 [&](const DiagnoseIfAttr *DIA) {
6453 APValue Result;
6454 // It's sane to use the same Args for any redecl of this function, since
6455 // EvaluateWithSubstitution only cares about the position of each
6456 // argument in the arg list, not the ParmVarDecl* it maps to.
6457 if (!DIA->getCond()->EvaluateWithSubstitution(
6458 Result, Context, cast<FunctionDecl>(DIA->getParent()), Args, ThisArg))
6459 return false;
6460 return Result.isInt() && Result.getInt().getBoolValue();
6461 });
6462}
6463
6464bool Sema::diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND,
6465 SourceLocation Loc) {
6466 return diagnoseDiagnoseIfAttrsWith(
6467 *this, ND, /*ArgDependent=*/false, Loc,
6468 [&](const DiagnoseIfAttr *DIA) {
6469 bool Result;
6470 return DIA->getCond()->EvaluateAsBooleanCondition(Result, Context) &&
6471 Result;
6472 });
6473}
6474
6475/// Add all of the function declarations in the given function set to
6476/// the overload candidate set.
6477void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
6478 ArrayRef<Expr *> Args,
6479 OverloadCandidateSet &CandidateSet,
6480 TemplateArgumentListInfo *ExplicitTemplateArgs,
6481 bool SuppressUserConversions,
6482 bool PartialOverloading,
6483 bool FirstArgumentIsBase) {
6484 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
6485 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
6486 ArrayRef<Expr *> FunctionArgs = Args;
6487
6488 FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D);
6489 FunctionDecl *FD =
6490 FunTmpl ? FunTmpl->getTemplatedDecl() : cast<FunctionDecl>(D);
6491
6492 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) {
6493 QualType ObjectType;
6494 Expr::Classification ObjectClassification;
6495 if (Args.size() > 0) {
6496 if (Expr *E = Args[0]) {
6497 // Use the explicit base to restrict the lookup:
6498 ObjectType = E->getType();
6499 // Pointers in the object arguments are implicitly dereferenced, so we
6500 // always classify them as l-values.
6501 if (!ObjectType.isNull() && ObjectType->isPointerType())
6502 ObjectClassification = Expr::Classification::makeSimpleLValue();
6503 else
6504 ObjectClassification = E->Classify(Context);
6505 } // .. else there is an implicit base.
6506 FunctionArgs = Args.slice(1);
6507 }
6508 if (FunTmpl) {
6509 AddMethodTemplateCandidate(
6510 FunTmpl, F.getPair(),
6511 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
6512 ExplicitTemplateArgs, ObjectType, ObjectClassification,
6513 FunctionArgs, CandidateSet, SuppressUserConversions,
6514 PartialOverloading);
6515 } else {
6516 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
6517 cast<CXXMethodDecl>(FD)->getParent(), ObjectType,
6518 ObjectClassification, FunctionArgs, CandidateSet,
6519 SuppressUserConversions, PartialOverloading);
6520 }
6521 } else {
6522 // This branch handles both standalone functions and static methods.
6523
6524 // Slice the first argument (which is the base) when we access
6525 // static method as non-static.
6526 if (Args.size() > 0 &&
6527 (!Args[0] || (FirstArgumentIsBase && isa<CXXMethodDecl>(FD) &&
6528 !isa<CXXConstructorDecl>(FD)))) {
6529 assert(cast<CXXMethodDecl>(FD)->isStatic());
6530 FunctionArgs = Args.slice(1);
6531 }
6532 if (FunTmpl) {
6533 AddTemplateOverloadCandidate(
6534 FunTmpl, F.getPair(), ExplicitTemplateArgs, FunctionArgs,
6535 CandidateSet, SuppressUserConversions, PartialOverloading);
6536 } else {
6537 AddOverloadCandidate(FD, F.getPair(), FunctionArgs, CandidateSet,
6538 SuppressUserConversions, PartialOverloading);
6539 }
6540 }
6541 }
6542}
6543
6544/// AddMethodCandidate - Adds a named decl (which is some kind of
6545/// method) as a method candidate to the given overload set.
6546void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
6547 QualType ObjectType,
6548 Expr::Classification ObjectClassification,
6549 ArrayRef<Expr *> Args,
6550 OverloadCandidateSet& CandidateSet,
6551 bool SuppressUserConversions) {
6552 NamedDecl *Decl = FoundDecl.getDecl();
6553 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
6554
6555 if (isa<UsingShadowDecl>(Decl))
6556 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
6557
6558 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
6559 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
6560 "Expected a member function template");
6561 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
6562 /*ExplicitArgs*/ nullptr, ObjectType,
6563 ObjectClassification, Args, CandidateSet,
6564 SuppressUserConversions);
6565 } else {
6566 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
6567 ObjectType, ObjectClassification, Args, CandidateSet,
6568 SuppressUserConversions);
6569 }
6570}
6571
6572/// AddMethodCandidate - Adds the given C++ member function to the set
6573/// of candidate functions, using the given function call arguments
6574/// and the object argument (@c Object). For example, in a call
6575/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
6576/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
6577/// allow user-defined conversions via constructors or conversion
6578/// operators.
6579void
6580Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
6581 CXXRecordDecl *ActingContext, QualType ObjectType,
6582 Expr::Classification ObjectClassification,
6583 ArrayRef<Expr *> Args,
6584 OverloadCandidateSet &CandidateSet,
6585 bool SuppressUserConversions,
6586 bool PartialOverloading,
6587 ConversionSequenceList EarlyConversions) {
6588 const FunctionProtoType *Proto
6589 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
6590 assert(Proto && "Methods without a prototype cannot be overloaded");
6591 assert(!isa<CXXConstructorDecl>(Method) &&
6592 "Use AddOverloadCandidate for constructors");
6593
6594 if (!CandidateSet.isNewCandidate(Method))
6595 return;
6596
6597 // C++11 [class.copy]p23: [DR1402]
6598 // A defaulted move assignment operator that is defined as deleted is
6599 // ignored by overload resolution.
6600 if (Method->isDefaulted() && Method->isDeleted() &&
6601 Method->isMoveAssignmentOperator())
6602 return;
6603
6604 // Overload resolution is always an unevaluated context.
6605 EnterExpressionEvaluationContext Unevaluated(
6606 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6607
6608 // Add this candidate
6609 OverloadCandidate &Candidate =
6610 CandidateSet.addCandidate(Args.size() + 1, EarlyConversions);
6611 Candidate.FoundDecl = FoundDecl;
6612 Candidate.Function = Method;
6613 Candidate.IsSurrogate = false;
6614 Candidate.IgnoreObjectArgument = false;
6615 Candidate.ExplicitCallArguments = Args.size();
6616
6617 unsigned NumParams = Proto->getNumParams();
6618
6619 // (C++ 13.3.2p2): A candidate function having fewer than m
6620 // parameters is viable only if it has an ellipsis in its parameter
6621 // list (8.3.5).
6622 if (TooManyArguments(NumParams, Args.size(), PartialOverloading) &&
6623 !Proto->isVariadic()) {
6624 Candidate.Viable = false;
6625 Candidate.FailureKind = ovl_fail_too_many_arguments;
6626 return;
6627 }
6628
6629 // (C++ 13.3.2p2): A candidate function having more than m parameters
6630 // is viable only if the (m+1)st parameter has a default argument
6631 // (8.3.6). For the purposes of overload resolution, the
6632 // parameter list is truncated on the right, so that there are
6633 // exactly m parameters.
6634 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
6635 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
6636 // Not enough arguments.
6637 Candidate.Viable = false;
6638 Candidate.FailureKind = ovl_fail_too_few_arguments;
6639 return;
6640 }
6641
6642 Candidate.Viable = true;
6643
6644 if (Method->isStatic() || ObjectType.isNull())
6645 // The implicit object argument is ignored.
6646 Candidate.IgnoreObjectArgument = true;
6647 else {
6648 // Determine the implicit conversion sequence for the object
6649 // parameter.
6650 Candidate.Conversions[0] = TryObjectArgumentInitialization(
6651 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6652 Method, ActingContext);
6653 if (Candidate.Conversions[0].isBad()) {
6654 Candidate.Viable = false;
6655 Candidate.FailureKind = ovl_fail_bad_conversion;
6656 return;
6657 }
6658 }
6659
6660 // (CUDA B.1): Check for invalid calls between targets.
6661 if (getLangOpts().CUDA)
6662 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
6663 if (!IsAllowedCUDACall(Caller, Method)) {
6664 Candidate.Viable = false;
6665 Candidate.FailureKind = ovl_fail_bad_target;
6666 return;
6667 }
6668
6669 // Determine the implicit conversion sequences for each of the
6670 // arguments.
6671 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
6672 if (Candidate.Conversions[ArgIdx + 1].isInitialized()) {
6673 // We already formed a conversion sequence for this parameter during
6674 // template argument deduction.
6675 } else if (ArgIdx < NumParams) {
6676 // (C++ 13.3.2p3): for F to be a viable function, there shall
6677 // exist for each argument an implicit conversion sequence
6678 // (13.3.3.1) that converts that argument to the corresponding
6679 // parameter of F.
6680 QualType ParamType = Proto->getParamType(ArgIdx);
6681 Candidate.Conversions[ArgIdx + 1]
6682 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
6683 SuppressUserConversions,
6684 /*InOverloadResolution=*/true,
6685 /*AllowObjCWritebackConversion=*/
6686 getLangOpts().ObjCAutoRefCount);
6687 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
6688 Candidate.Viable = false;
6689 Candidate.FailureKind = ovl_fail_bad_conversion;
6690 return;
6691 }
6692 } else {
6693 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6694 // argument for which there is no corresponding parameter is
6695 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
6696 Candidate.Conversions[ArgIdx + 1].setEllipsis();
6697 }
6698 }
6699
6700 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
6701 Candidate.Viable = false;
6702 Candidate.FailureKind = ovl_fail_enable_if;
6703 Candidate.DeductionFailure.Data = FailedAttr;
6704 return;
6705 }
6706
6707 if (Method->isMultiVersion() && Method->hasAttr<TargetAttr>() &&
6708 !Method->getAttr<TargetAttr>()->isDefaultVersion()) {
6709 Candidate.Viable = false;
6710 Candidate.FailureKind = ovl_non_default_multiversion_function;
6711 }
6712}
6713
6714/// Add a C++ member function template as a candidate to the candidate
6715/// set, using template argument deduction to produce an appropriate member
6716/// function template specialization.
6717void
6718Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
6719 DeclAccessPair FoundDecl,
6720 CXXRecordDecl *ActingContext,
6721 TemplateArgumentListInfo *ExplicitTemplateArgs,
6722 QualType ObjectType,
6723 Expr::Classification ObjectClassification,
6724 ArrayRef<Expr *> Args,
6725 OverloadCandidateSet& CandidateSet,
6726 bool SuppressUserConversions,
6727 bool PartialOverloading) {
6728 if (!CandidateSet.isNewCandidate(MethodTmpl))
6729 return;
6730
6731 // C++ [over.match.funcs]p7:
6732 // In each case where a candidate is a function template, candidate
6733 // function template specializations are generated using template argument
6734 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6735 // candidate functions in the usual way.113) A given name can refer to one
6736 // or more function templates and also to a set of overloaded non-template
6737 // functions. In such a case, the candidate functions generated from each
6738 // function template are combined with the set of non-template candidate
6739 // functions.
6740 TemplateDeductionInfo Info(CandidateSet.getLocation());
6741 FunctionDecl *Specialization = nullptr;
6742 ConversionSequenceList Conversions;
6743 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6744 MethodTmpl, ExplicitTemplateArgs, Args, Specialization, Info,
6745 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6746 return CheckNonDependentConversions(
6747 MethodTmpl, ParamTypes, Args, CandidateSet, Conversions,
6748 SuppressUserConversions, ActingContext, ObjectType,
6749 ObjectClassification);
6750 })) {
6751 OverloadCandidate &Candidate =
6752 CandidateSet.addCandidate(Conversions.size(), Conversions);
6753 Candidate.FoundDecl = FoundDecl;
6754 Candidate.Function = MethodTmpl->getTemplatedDecl();
6755 Candidate.Viable = false;
6756 Candidate.IsSurrogate = false;
6757 Candidate.IgnoreObjectArgument =
6758 cast<CXXMethodDecl>(Candidate.Function)->isStatic() ||
6759 ObjectType.isNull();
6760 Candidate.ExplicitCallArguments = Args.size();
6761 if (Result == TDK_NonDependentConversionFailure)
6762 Candidate.FailureKind = ovl_fail_bad_conversion;
6763 else {
6764 Candidate.FailureKind = ovl_fail_bad_deduction;
6765 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6766 Info);
6767 }
6768 return;
6769 }
6770
6771 // Add the function template specialization produced by template argument
6772 // deduction as a candidate.
6773 assert(Specialization && "Missing member function template specialization?");
6774 assert(isa<CXXMethodDecl>(Specialization) &&
6775 "Specialization is not a member function?");
6776 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
6777 ActingContext, ObjectType, ObjectClassification, Args,
6778 CandidateSet, SuppressUserConversions, PartialOverloading,
6779 Conversions);
6780}
6781
6782/// Add a C++ function template specialization as a candidate
6783/// in the candidate set, using template argument deduction to produce
6784/// an appropriate function template specialization.
6785void Sema::AddTemplateOverloadCandidate(
6786 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
6787 TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
6788 OverloadCandidateSet &CandidateSet, bool SuppressUserConversions,
6789 bool PartialOverloading, bool AllowExplicit, ADLCallKind IsADLCandidate) {
6790 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6791 return;
6792
6793 // C++ [over.match.funcs]p7:
6794 // In each case where a candidate is a function template, candidate
6795 // function template specializations are generated using template argument
6796 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
6797 // candidate functions in the usual way.113) A given name can refer to one
6798 // or more function templates and also to a set of overloaded non-template
6799 // functions. In such a case, the candidate functions generated from each
6800 // function template are combined with the set of non-template candidate
6801 // functions.
6802 TemplateDeductionInfo Info(CandidateSet.getLocation());
6803 FunctionDecl *Specialization = nullptr;
6804 ConversionSequenceList Conversions;
6805 if (TemplateDeductionResult Result = DeduceTemplateArguments(
6806 FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info,
6807 PartialOverloading, [&](ArrayRef<QualType> ParamTypes) {
6808 return CheckNonDependentConversions(FunctionTemplate, ParamTypes,
6809 Args, CandidateSet, Conversions,
6810 SuppressUserConversions);
6811 })) {
6812 OverloadCandidate &Candidate =
6813 CandidateSet.addCandidate(Conversions.size(), Conversions);
6814 Candidate.FoundDecl = FoundDecl;
6815 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6816 Candidate.Viable = false;
6817 Candidate.IsSurrogate = false;
6818 Candidate.IsADLCandidate = IsADLCandidate;
6819 // Ignore the object argument if there is one, since we don't have an object
6820 // type.
6821 Candidate.IgnoreObjectArgument =
6822 isa<CXXMethodDecl>(Candidate.Function) &&
6823 !isa<CXXConstructorDecl>(Candidate.Function);
6824 Candidate.ExplicitCallArguments = Args.size();
6825 if (Result == TDK_NonDependentConversionFailure)
6826 Candidate.FailureKind = ovl_fail_bad_conversion;
6827 else {
6828 Candidate.FailureKind = ovl_fail_bad_deduction;
6829 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
6830 Info);
6831 }
6832 return;
6833 }
6834
6835 // Add the function template specialization produced by template argument
6836 // deduction as a candidate.
6837 assert(Specialization && "Missing function template specialization?");
6838 AddOverloadCandidate(
6839 Specialization, FoundDecl, Args, CandidateSet, SuppressUserConversions,
6840 PartialOverloading, AllowExplicit,
6841 /*AllowExplicitConversions*/ false, IsADLCandidate, Conversions);
6842}
6843
6844/// Check that implicit conversion sequences can be formed for each argument
6845/// whose corresponding parameter has a non-dependent type, per DR1391's
6846/// [temp.deduct.call]p10.
6847bool Sema::CheckNonDependentConversions(
6848 FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes,
6849 ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet,
6850 ConversionSequenceList &Conversions, bool SuppressUserConversions,
6851 CXXRecordDecl *ActingContext, QualType ObjectType,
6852 Expr::Classification ObjectClassification) {
6853 // FIXME: The cases in which we allow explicit conversions for constructor
6854 // arguments never consider calling a constructor template. It's not clear
6855 // that is correct.
6856 const bool AllowExplicit = false;
6857
6858 auto *FD = FunctionTemplate->getTemplatedDecl();
6859 auto *Method = dyn_cast<CXXMethodDecl>(FD);
6860 bool HasThisConversion = Method && !isa<CXXConstructorDecl>(Method);
6861 unsigned ThisConversions = HasThisConversion ? 1 : 0;
6862
6863 Conversions =
6864 CandidateSet.allocateConversionSequences(ThisConversions + Args.size());
6865
6866 // Overload resolution is always an unevaluated context.
6867 EnterExpressionEvaluationContext Unevaluated(
6868 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6869
6870 // For a method call, check the 'this' conversion here too. DR1391 doesn't
6871 // require that, but this check should never result in a hard error, and
6872 // overload resolution is permitted to sidestep instantiations.
6873 if (HasThisConversion && !cast<CXXMethodDecl>(FD)->isStatic() &&
6874 !ObjectType.isNull()) {
6875 Conversions[0] = TryObjectArgumentInitialization(
6876 *this, CandidateSet.getLocation(), ObjectType, ObjectClassification,
6877 Method, ActingContext);
6878 if (Conversions[0].isBad())
6879 return true;
6880 }
6881
6882 for (unsigned I = 0, N = std::min(ParamTypes.size(), Args.size()); I != N;
6883 ++I) {
6884 QualType ParamType = ParamTypes[I];
6885 if (!ParamType->isDependentType()) {
6886 Conversions[ThisConversions + I]
6887 = TryCopyInitialization(*this, Args[I], ParamType,
6888 SuppressUserConversions,
6889 /*InOverloadResolution=*/true,
6890 /*AllowObjCWritebackConversion=*/
6891 getLangOpts().ObjCAutoRefCount,
6892 AllowExplicit);
6893 if (Conversions[ThisConversions + I].isBad())
6894 return true;
6895 }
6896 }
6897
6898 return false;
6899}
6900
6901/// Determine whether this is an allowable conversion from the result
6902/// of an explicit conversion operator to the expected type, per C++
6903/// [over.match.conv]p1 and [over.match.ref]p1.
6904///
6905/// \param ConvType The return type of the conversion function.
6906///
6907/// \param ToType The type we are converting to.
6908///
6909/// \param AllowObjCPointerConversion Allow a conversion from one
6910/// Objective-C pointer to another.
6911///
6912/// \returns true if the conversion is allowable, false otherwise.
6913static bool isAllowableExplicitConversion(Sema &S,
6914 QualType ConvType, QualType ToType,
6915 bool AllowObjCPointerConversion) {
6916 QualType ToNonRefType = ToType.getNonReferenceType();
6917
6918 // Easy case: the types are the same.
6919 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6920 return true;
6921
6922 // Allow qualification conversions.
6923 bool ObjCLifetimeConversion;
6924 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6925 ObjCLifetimeConversion))
6926 return true;
6927
6928 // If we're not allowed to consider Objective-C pointer conversions,
6929 // we're done.
6930 if (!AllowObjCPointerConversion)
6931 return false;
6932
6933 // Is this an Objective-C pointer conversion?
6934 bool IncompatibleObjC = false;
6935 QualType ConvertedType;
6936 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6937 IncompatibleObjC);
6938}
6939
6940/// AddConversionCandidate - Add a C++ conversion function as a
6941/// candidate in the candidate set (C++ [over.match.conv],
6942/// C++ [over.match.copy]). From is the expression we're converting from,
6943/// and ToType is the type that we're eventually trying to convert to
6944/// (which may or may not be the same type as the type that the
6945/// conversion function produces).
6946void Sema::AddConversionCandidate(
6947 CXXConversionDecl *Conversion, DeclAccessPair FoundDecl,
6948 CXXRecordDecl *ActingContext, Expr *From, QualType ToType,
6949 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
6950 bool AllowExplicit, bool AllowResultConversion) {
6951 assert(!Conversion->getDescribedFunctionTemplate() &&
6952 "Conversion function templates use AddTemplateConversionCandidate");
6953 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
6954 if (!CandidateSet.isNewCandidate(Conversion))
6955 return;
6956
6957 // If the conversion function has an undeduced return type, trigger its
6958 // deduction now.
6959 if (getLangOpts().CPlusPlus14 && ConvType->isUndeducedType()) {
6960 if (DeduceReturnType(Conversion, From->getExprLoc()))
6961 return;
6962 ConvType = Conversion->getConversionType().getNonReferenceType();
6963 }
6964
6965 // If we don't allow any conversion of the result type, ignore conversion
6966 // functions that don't convert to exactly (possibly cv-qualified) T.
6967 if (!AllowResultConversion &&
6968 !Context.hasSameUnqualifiedType(Conversion->getConversionType(), ToType))
6969 return;
6970
6971 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6972 // operator is only a candidate if its return type is the target type or
6973 // can be converted to the target type with a qualification conversion.
6974 if (Conversion->isExplicit() &&
6975 !isAllowableExplicitConversion(*this, ConvType, ToType,
6976 AllowObjCConversionOnExplicit))
6977 return;
6978
6979 // Overload resolution is always an unevaluated context.
6980 EnterExpressionEvaluationContext Unevaluated(
6981 *this, Sema::ExpressionEvaluationContext::Unevaluated);
6982
6983 // Add this candidate
6984 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
6985 Candidate.FoundDecl = FoundDecl;
6986 Candidate.Function = Conversion;
6987 Candidate.IsSurrogate = false;
6988 Candidate.IgnoreObjectArgument = false;
6989 Candidate.FinalConversion.setAsIdentityConversion();
6990 Candidate.FinalConversion.setFromType(ConvType);
6991 Candidate.FinalConversion.setAllToTypes(ToType);
6992 Candidate.Viable = true;
6993 Candidate.ExplicitCallArguments = 1;
6994
6995 // C++ [over.match.funcs]p4:
6996 // For conversion functions, the function is considered to be a member of
6997 // the class of the implicit implied object argument for the purpose of
6998 // defining the type of the implicit object parameter.
6999 //
7000 // Determine the implicit conversion sequence for the implicit
7001 // object parameter.
7002 QualType ImplicitParamType = From->getType();
7003 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
7004 ImplicitParamType = FromPtrType->getPointeeType();
7005 CXXRecordDecl *ConversionContext
7006 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
7007
7008 Candidate.Conversions[0] = TryObjectArgumentInitialization(
7009 *this, CandidateSet.getLocation(), From->getType(),
7010 From->Classify(Context), Conversion, ConversionContext);
7011
7012 if (Candidate.Conversions[0].isBad()) {
7013 Candidate.Viable = false;
7014 Candidate.FailureKind = ovl_fail_bad_conversion;
7015 return;
7016 }
7017
7018 // We won't go through a user-defined type conversion function to convert a
7019 // derived to base as such conversions are given Conversion Rank. They only
7020 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
7021 QualType FromCanon
7022 = Context.getCanonicalType(From->getType().getUnqualifiedType());
7023 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
7024 if (FromCanon == ToCanon ||
7025 IsDerivedFrom(CandidateSet.getLocation(), FromCanon, ToCanon)) {
7026 Candidate.Viable = false;
7027 Candidate.FailureKind = ovl_fail_trivial_conversion;
7028 return;
7029 }
7030
7031 // To determine what the conversion from the result of calling the
7032 // conversion function to the type we're eventually trying to
7033 // convert to (ToType), we need to synthesize a call to the
7034 // conversion function and attempt copy initialization from it. This
7035 // makes sure that we get the right semantics with respect to
7036 // lvalues/rvalues and the type. Fortunately, we can allocate this
7037 // call on the stack and we don't need its arguments to be
7038 // well-formed.
7039 DeclRefExpr ConversionRef(Context, Conversion, false, Conversion->getType(),
7040 VK_LValue, From->getBeginLoc());
7041 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
7042 Context.getPointerType(Conversion->getType()),
7043 CK_FunctionToPointerDecay,
7044 &ConversionRef, VK_RValue);
7045
7046 QualType ConversionType = Conversion->getConversionType();
7047 if (!isCompleteType(From->getBeginLoc(), ConversionType)) {
7048 Candidate.Viable = false;
7049 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7050 return;
7051 }
7052
7053 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
7054
7055 // Note that it is safe to allocate CallExpr on the stack here because
7056 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
7057 // allocator).
7058 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
7059
7060 llvm::AlignedCharArray<alignof(CallExpr), sizeof(CallExpr) + sizeof(Stmt *)>
7061 Buffer;
7062 CallExpr *TheTemporaryCall = CallExpr::CreateTemporary(
7063 Buffer.buffer, &ConversionFn, CallResultType, VK, From->getBeginLoc());
7064
7065 ImplicitConversionSequence ICS =
7066 TryCopyInitialization(*this, TheTemporaryCall, ToType,
7067 /*SuppressUserConversions=*/true,
7068 /*InOverloadResolution=*/false,
7069 /*AllowObjCWritebackConversion=*/false);
7070
7071 switch (ICS.getKind()) {
7072 case ImplicitConversionSequence::StandardConversion:
7073 Candidate.FinalConversion = ICS.Standard;
7074
7075 // C++ [over.ics.user]p3:
7076 // If the user-defined conversion is specified by a specialization of a
7077 // conversion function template, the second standard conversion sequence
7078 // shall have exact match rank.
7079 if (Conversion->getPrimaryTemplate() &&
7080 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
7081 Candidate.Viable = false;
7082 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
7083 return;
7084 }
7085
7086 // C++0x [dcl.init.ref]p5:
7087 // In the second case, if the reference is an rvalue reference and
7088 // the second standard conversion sequence of the user-defined
7089 // conversion sequence includes an lvalue-to-rvalue conversion, the
7090 // program is ill-formed.
7091 if (ToType->isRValueReferenceType() &&
7092 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
7093 Candidate.Viable = false;
7094 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7095 return;
7096 }
7097 break;
7098
7099 case ImplicitConversionSequence::BadConversion:
7100 Candidate.Viable = false;
7101 Candidate.FailureKind = ovl_fail_bad_final_conversion;
7102 return;
7103
7104 default:
7105 llvm_unreachable(
7106 "Can only end up with a standard conversion sequence or failure");
7107 }
7108
7109 if (!AllowExplicit && Conversion->getExplicitSpecifier().getKind() !=
7110 ExplicitSpecKind::ResolvedFalse) {
7111 Candidate.Viable = false;
7112 Candidate.FailureKind = ovl_fail_explicit_resolved;
7113 return;
7114 }
7115
7116 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7117 Candidate.Viable = false;
7118 Candidate.FailureKind = ovl_fail_enable_if;
7119 Candidate.DeductionFailure.Data = FailedAttr;
7120 return;
7121 }
7122
7123 if (Conversion->isMultiVersion() && Conversion->hasAttr<TargetAttr>() &&
7124 !Conversion->getAttr<TargetAttr>()->isDefaultVersion()) {
7125 Candidate.Viable = false;
7126 Candidate.FailureKind = ovl_non_default_multiversion_function;
7127 }
7128}
7129
7130/// Adds a conversion function template specialization
7131/// candidate to the overload set, using template argument deduction
7132/// to deduce the template arguments of the conversion function
7133/// template from the type that we are converting to (C++
7134/// [temp.deduct.conv]).
7135void Sema::AddTemplateConversionCandidate(
7136 FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl,
7137 CXXRecordDecl *ActingDC, Expr *From, QualType ToType,
7138 OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit,
7139 bool AllowExplicit, bool AllowResultConversion) {
7140 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
7141 "Only conversion function templates permitted here");
7142
7143 if (!CandidateSet.isNewCandidate(FunctionTemplate))
7144 return;
7145
7146 TemplateDeductionInfo Info(CandidateSet.getLocation());
7147 CXXConversionDecl *Specialization = nullptr;
7148 if (TemplateDeductionResult Result
7149 = DeduceTemplateArguments(FunctionTemplate, ToType,
7150 Specialization, Info)) {
7151 OverloadCandidate &Candidate = CandidateSet.addCandidate();
7152 Candidate.FoundDecl = FoundDecl;
7153 Candidate.Function = FunctionTemplate->getTemplatedDecl();
7154 Candidate.Viable = false;
7155 Candidate.FailureKind = ovl_fail_bad_deduction;
7156 Candidate.IsSurrogate = false;
7157 Candidate.IgnoreObjectArgument = false;
7158 Candidate.ExplicitCallArguments = 1;
7159 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
7160 Info);
7161 return;
7162 }
7163
7164 // Add the conversion function template specialization produced by
7165 // template argument deduction as a candidate.
7166 assert(Specialization && "Missing function template specialization?");
7167 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
7168 CandidateSet, AllowObjCConversionOnExplicit,
7169 AllowExplicit, AllowResultConversion);
7170}
7171
7172/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
7173/// converts the given @c Object to a function pointer via the
7174/// conversion function @c Conversion, and then attempts to call it
7175/// with the given arguments (C++ [over.call.object]p2-4). Proto is
7176/// the type of function that we'll eventually be calling.
7177void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
7178 DeclAccessPair FoundDecl,
7179 CXXRecordDecl *ActingContext,
7180 const FunctionProtoType *Proto,
7181 Expr *Object,
7182 ArrayRef<Expr *> Args,
7183 OverloadCandidateSet& CandidateSet) {
7184 if (!CandidateSet.isNewCandidate(Conversion))
7185 return;
7186
7187 // Overload resolution is always an unevaluated context.
7188 EnterExpressionEvaluationContext Unevaluated(
7189 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7190
7191 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
7192 Candidate.FoundDecl = FoundDecl;
7193 Candidate.Function = nullptr;
7194 Candidate.Surrogate = Conversion;
7195 Candidate.Viable = true;
7196 Candidate.IsSurrogate = true;
7197 Candidate.IgnoreObjectArgument = false;
7198 Candidate.ExplicitCallArguments = Args.size();
7199
7200 // Determine the implicit conversion sequence for the implicit
7201 // object parameter.
7202 ImplicitConversionSequence ObjectInit = TryObjectArgumentInitialization(
7203 *this, CandidateSet.getLocation(), Object->getType(),
7204 Object->Classify(Context), Conversion, ActingContext);
7205 if (ObjectInit.isBad()) {
7206 Candidate.Viable = false;
7207 Candidate.FailureKind = ovl_fail_bad_conversion;
7208 Candidate.Conversions[0] = ObjectInit;
7209 return;
7210 }
7211
7212 // The first conversion is actually a user-defined conversion whose
7213 // first conversion is ObjectInit's standard conversion (which is
7214 // effectively a reference binding). Record it as such.
7215 Candidate.Conversions[0].setUserDefined();
7216 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
7217 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
7218 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
7219 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
7220 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
7221 Candidate.Conversions[0].UserDefined.After
7222 = Candidate.Conversions[0].UserDefined.Before;
7223 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
7224
7225 // Find the
7226 unsigned NumParams = Proto->getNumParams();
7227
7228 // (C++ 13.3.2p2): A candidate function having fewer than m
7229 // parameters is viable only if it has an ellipsis in its parameter
7230 // list (8.3.5).
7231 if (Args.size() > NumParams && !Proto->isVariadic()) {
7232 Candidate.Viable = false;
7233 Candidate.FailureKind = ovl_fail_too_many_arguments;
7234 return;
7235 }
7236
7237 // Function types don't have any default arguments, so just check if
7238 // we have enough arguments.
7239 if (Args.size() < NumParams) {
7240 // Not enough arguments.
7241 Candidate.Viable = false;
7242 Candidate.FailureKind = ovl_fail_too_few_arguments;
7243 return;
7244 }
7245
7246 // Determine the implicit conversion sequences for each of the
7247 // arguments.
7248 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7249 if (ArgIdx < NumParams) {
7250 // (C++ 13.3.2p3): for F to be a viable function, there shall
7251 // exist for each argument an implicit conversion sequence
7252 // (13.3.3.1) that converts that argument to the corresponding
7253 // parameter of F.
7254 QualType ParamType = Proto->getParamType(ArgIdx);
7255 Candidate.Conversions[ArgIdx + 1]
7256 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
7257 /*SuppressUserConversions=*/false,
7258 /*InOverloadResolution=*/false,
7259 /*AllowObjCWritebackConversion=*/
7260 getLangOpts().ObjCAutoRefCount);
7261 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
7262 Candidate.Viable = false;
7263 Candidate.FailureKind = ovl_fail_bad_conversion;
7264 return;
7265 }
7266 } else {
7267 // (C++ 13.3.2p2): For the purposes of overload resolution, any
7268 // argument for which there is no corresponding parameter is
7269 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
7270 Candidate.Conversions[ArgIdx + 1].setEllipsis();
7271 }
7272 }
7273
7274 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, None)) {
7275 Candidate.Viable = false;
7276 Candidate.FailureKind = ovl_fail_enable_if;
7277 Candidate.DeductionFailure.Data = FailedAttr;
7278 return;
7279 }
7280}
7281
7282/// Add overload candidates for overloaded operators that are
7283/// member functions.
7284///
7285/// Add the overloaded operator candidates that are member functions
7286/// for the operator Op that was used in an operator expression such
7287/// as "x Op y". , Args/NumArgs provides the operator arguments, and
7288/// CandidateSet will store the added overload candidates. (C++
7289/// [over.match.oper]).
7290void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
7291 SourceLocation OpLoc,
7292 ArrayRef<Expr *> Args,
7293 OverloadCandidateSet& CandidateSet,
7294 SourceRange OpRange) {
7295 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7296
7297 // C++ [over.match.oper]p3:
7298 // For a unary operator @ with an operand of a type whose
7299 // cv-unqualified version is T1, and for a binary operator @ with
7300 // a left operand of a type whose cv-unqualified version is T1 and
7301 // a right operand of a type whose cv-unqualified version is T2,
7302 // three sets of candidate functions, designated member
7303 // candidates, non-member candidates and built-in candidates, are
7304 // constructed as follows:
7305 QualType T1 = Args[0]->getType();
7306
7307 // -- If T1 is a complete class type or a class currently being
7308 // defined, the set of member candidates is the result of the
7309 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
7310 // the set of member candidates is empty.
7311 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
7312 // Complete the type if it can be completed.
7313 if (!isCompleteType(OpLoc, T1) && !T1Rec->isBeingDefined())
7314 return;
7315 // If the type is neither complete nor being defined, bail out now.
7316 if (!T1Rec->getDecl()->getDefinition())
7317 return;
7318
7319 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
7320 LookupQualifiedName(Operators, T1Rec->getDecl());
7321 Operators.suppressDiagnostics();
7322
7323 for (LookupResult::iterator Oper = Operators.begin(),
7324 OperEnd = Operators.end();
7325 Oper != OperEnd;
7326 ++Oper)
7327 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
7328 Args[0]->Classify(Context), Args.slice(1),
7329 CandidateSet, /*SuppressUserConversions=*/false);
7330 }
7331}
7332
7333/// AddBuiltinCandidate - Add a candidate for a built-in
7334/// operator. ResultTy and ParamTys are the result and parameter types
7335/// of the built-in candidate, respectively. Args and NumArgs are the
7336/// arguments being passed to the candidate. IsAssignmentOperator
7337/// should be true when this built-in candidate is an assignment
7338/// operator. NumContextualBoolArguments is the number of arguments
7339/// (at the beginning of the argument list) that will be contextually
7340/// converted to bool.
7341void Sema::AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args,
7342 OverloadCandidateSet& CandidateSet,
7343 bool IsAssignmentOperator,
7344 unsigned NumContextualBoolArguments) {
7345 // Overload resolution is always an unevaluated context.
7346 EnterExpressionEvaluationContext Unevaluated(
7347 *this, Sema::ExpressionEvaluationContext::Unevaluated);
7348
7349 // Add this candidate
7350 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
7351 Candidate.FoundDecl = DeclAccessPair::make(nullptr, AS_none);
7352 Candidate.Function = nullptr;
7353 Candidate.IsSurrogate = false;
7354 Candidate.IgnoreObjectArgument = false;
7355 std::copy(ParamTys, ParamTys + Args.size(), Candidate.BuiltinParamTypes);
7356
7357 // Determine the implicit conversion sequences for each of the
7358 // arguments.
7359 Candidate.Viable = true;
7360 Candidate.ExplicitCallArguments = Args.size();
7361 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
7362 // C++ [over.match.oper]p4:
7363 // For the built-in assignment operators, conversions of the
7364 // left operand are restricted as follows:
7365 // -- no temporaries are introduced to hold the left operand, and
7366 // -- no user-defined conversions are applied to the left
7367 // operand to achieve a type match with the left-most
7368 // parameter of a built-in candidate.
7369 //
7370 // We block these conversions by turning off user-defined
7371 // conversions, since that is the only way that initialization of
7372 // a reference to a non-class type can occur from something that
7373 // is not of the same type.
7374 if (ArgIdx < NumContextualBoolArguments) {
7375 assert(ParamTys[ArgIdx] == Context.BoolTy &&
7376 "Contextual conversion to bool requires bool type");
7377 Candidate.Conversions[ArgIdx]
7378 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
7379 } else {
7380 Candidate.Conversions[ArgIdx]
7381 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
7382 ArgIdx == 0 && IsAssignmentOperator,
7383 /*InOverloadResolution=*/false,
7384 /*AllowObjCWritebackConversion=*/
7385 getLangOpts().ObjCAutoRefCount);
7386 }
7387 if (Candidate.Conversions[ArgIdx].isBad()) {
7388 Candidate.Viable = false;
7389 Candidate.FailureKind = ovl_fail_bad_conversion;
7390 break;
7391 }
7392 }
7393}
7394
7395namespace {
7396
7397/// BuiltinCandidateTypeSet - A set of types that will be used for the
7398/// candidate operator functions for built-in operators (C++
7399/// [over.built]). The types are separated into pointer types and
7400/// enumeration types.
7401class BuiltinCandidateTypeSet {
7402 /// TypeSet - A set of types.
7403 typedef llvm::SetVector<QualType, SmallVector<QualType, 8>,
7404 llvm::SmallPtrSet<QualType, 8>> TypeSet;
7405
7406 /// PointerTypes - The set of pointer types that will be used in the
7407 /// built-in candidates.
7408 TypeSet PointerTypes;
7409
7410 /// MemberPointerTypes - The set of member pointer types that will be
7411 /// used in the built-in candidates.
7412 TypeSet MemberPointerTypes;
7413
7414 /// EnumerationTypes - The set of enumeration types that will be
7415 /// used in the built-in candidates.
7416 TypeSet EnumerationTypes;
7417
7418 /// The set of vector types that will be used in the built-in
7419 /// candidates.
7420 TypeSet VectorTypes;
7421
7422 /// A flag indicating non-record types are viable candidates
7423 bool HasNonRecordTypes;
7424
7425 /// A flag indicating whether either arithmetic or enumeration types
7426 /// were present in the candidate set.
7427 bool HasArithmeticOrEnumeralTypes;
7428
7429 /// A flag indicating whether the nullptr type was present in the
7430 /// candidate set.
7431 bool HasNullPtrType;
7432
7433 /// Sema - The semantic analysis instance where we are building the
7434 /// candidate type set.
7435 Sema &SemaRef;
7436
7437 /// Context - The AST context in which we will build the type sets.
7438 ASTContext &Context;
7439
7440 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7441 const Qualifiers &VisibleQuals);
7442 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
7443
7444public:
7445 /// iterator - Iterates through the types that are part of the set.
7446 typedef TypeSet::iterator iterator;
7447
7448 BuiltinCandidateTypeSet(Sema &SemaRef)
7449 : HasNonRecordTypes(false),
7450 HasArithmeticOrEnumeralTypes(false),
7451 HasNullPtrType(false),
7452 SemaRef(SemaRef),
7453 Context(SemaRef.Context) { }
7454
7455 void AddTypesConvertedFrom(QualType Ty,
7456 SourceLocation Loc,
7457 bool AllowUserConversions,
7458 bool AllowExplicitConversions,
7459 const Qualifiers &VisibleTypeConversionsQuals);
7460
7461 /// pointer_begin - First pointer type found;
7462 iterator pointer_begin() { return PointerTypes.begin(); }
7463
7464 /// pointer_end - Past the last pointer type found;
7465 iterator pointer_end() { return PointerTypes.end(); }
7466
7467 /// member_pointer_begin - First member pointer type found;
7468 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
7469
7470 /// member_pointer_end - Past the last member pointer type found;
7471 iterator member_pointer_end() { return MemberPointerTypes.end(); }
7472
7473 /// enumeration_begin - First enumeration type found;
7474 iterator enumeration_begin() { return EnumerationTypes.begin(); }
7475
7476 /// enumeration_end - Past the last enumeration type found;
7477 iterator enumeration_end() { return EnumerationTypes.end(); }
7478
7479 iterator vector_begin() { return VectorTypes.begin(); }
7480 iterator vector_end() { return VectorTypes.end(); }
7481
7482 bool hasNonRecordTypes() { return HasNonRecordTypes; }
7483 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
7484 bool hasNullPtrType() const { return HasNullPtrType; }
7485};
7486
7487} // end anonymous namespace
7488
7489/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
7490/// the set of pointer types along with any more-qualified variants of
7491/// that type. For example, if @p Ty is "int const *", this routine
7492/// will add "int const *", "int const volatile *", "int const
7493/// restrict *", and "int const volatile restrict *" to the set of
7494/// pointer types. Returns true if the add of @p Ty itself succeeded,
7495/// false otherwise.
7496///
7497/// FIXME: what to do about extended qualifiers?
7498bool
7499BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
7500 const Qualifiers &VisibleQuals) {
7501
7502 // Insert this type.
7503 if (!PointerTypes.insert(Ty))
7504 return false;
7505
7506 QualType PointeeTy;
7507 const PointerType *PointerTy = Ty->getAs<PointerType>();
7508 bool buildObjCPtr = false;
7509 if (!PointerTy) {
7510 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
7511 PointeeTy = PTy->getPointeeType();
7512 buildObjCPtr = true;
7513 } else {
7514 PointeeTy = PointerTy->getPointeeType();
7515 }
7516
7517 // Don't add qualified variants of arrays. For one, they're not allowed
7518 // (the qualifier would sink to the element type), and for another, the
7519 // only overload situation where it matters is subscript or pointer +- int,
7520 // and those shouldn't have qualifier variants anyway.
7521 if (PointeeTy->isArrayType())
7522 return true;
7523
7524 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7525 bool hasVolatile = VisibleQuals.hasVolatile();
7526 bool hasRestrict = VisibleQuals.hasRestrict();
7527
7528 // Iterate through all strict supersets of BaseCVR.
7529 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7530 if ((CVR | BaseCVR) != CVR) continue;
7531 // Skip over volatile if no volatile found anywhere in the types.
7532 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
7533
7534 // Skip over restrict if no restrict found anywhere in the types, or if
7535 // the type cannot be restrict-qualified.
7536 if ((CVR & Qualifiers::Restrict) &&
7537 (!hasRestrict ||
7538 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
7539 continue;
7540
7541 // Build qualified pointee type.
7542 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7543
7544 // Build qualified pointer type.
7545 QualType QPointerTy;
7546 if (!buildObjCPtr)
7547 QPointerTy = Context.getPointerType(QPointeeTy);
7548 else
7549 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
7550
7551 // Insert qualified pointer type.
7552 PointerTypes.insert(QPointerTy);
7553 }
7554
7555 return true;
7556}
7557
7558/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
7559/// to the set of pointer types along with any more-qualified variants of
7560/// that type. For example, if @p Ty is "int const *", this routine
7561/// will add "int const *", "int const volatile *", "int const
7562/// restrict *", and "int const volatile restrict *" to the set of
7563/// pointer types. Returns true if the add of @p Ty itself succeeded,
7564/// false otherwise.
7565///
7566/// FIXME: what to do about extended qualifiers?
7567bool
7568BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
7569 QualType Ty) {
7570 // Insert this type.
7571 if (!MemberPointerTypes.insert(Ty))
7572 return false;
7573
7574 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
7575 assert(PointerTy && "type was not a member pointer type!");
7576
7577 QualType PointeeTy = PointerTy->getPointeeType();
7578 // Don't add qualified variants of arrays. For one, they're not allowed
7579 // (the qualifier would sink to the element type), and for another, the
7580 // only overload situation where it matters is subscript or pointer +- int,
7581 // and those shouldn't have qualifier variants anyway.
7582 if (PointeeTy->isArrayType())
7583 return true;
7584 const Type *ClassTy = PointerTy->getClass();
7585
7586 // Iterate through all strict supersets of the pointee type's CVR
7587 // qualifiers.
7588 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
7589 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
7590 if ((CVR | BaseCVR) != CVR) continue;
7591
7592 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
7593 MemberPointerTypes.insert(
7594 Context.getMemberPointerType(QPointeeTy, ClassTy));
7595 }
7596
7597 return true;
7598}
7599
7600/// AddTypesConvertedFrom - Add each of the types to which the type @p
7601/// Ty can be implicit converted to the given set of @p Types. We're
7602/// primarily interested in pointer types and enumeration types. We also
7603/// take member pointer types, for the conditional operator.
7604/// AllowUserConversions is true if we should look at the conversion
7605/// functions of a class type, and AllowExplicitConversions if we
7606/// should also include the explicit conversion functions of a class
7607/// type.
7608void
7609BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
7610 SourceLocation Loc,
7611 bool AllowUserConversions,
7612 bool AllowExplicitConversions,
7613 const Qualifiers &VisibleQuals) {
7614 // Only deal with canonical types.
7615 Ty = Context.getCanonicalType(Ty);
7616
7617 // Look through reference types; they aren't part of the type of an
7618 // expression for the purposes of conversions.
7619 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
7620 Ty = RefTy->getPointeeType();
7621
7622 // If we're dealing with an array type, decay to the pointer.
7623 if (Ty->isArrayType())
7624 Ty = SemaRef.Context.getArrayDecayedType(Ty);
7625
7626 // Otherwise, we don't care about qualifiers on the type.
7627 Ty = Ty.getLocalUnqualifiedType();
7628
7629 // Flag if we ever add a non-record type.
7630 const RecordType *TyRec = Ty->getAs<RecordType>();
7631 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
7632
7633 // Flag if we encounter an arithmetic type.
7634 HasArithmeticOrEnumeralTypes =
7635 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
7636
7637 if (Ty->isObjCIdType() || Ty->isObjCClassType())
7638 PointerTypes.insert(Ty);
7639 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
7640 // Insert our type, and its more-qualified variants, into the set
7641 // of types.
7642 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
7643 return;
7644 } else if (Ty->isMemberPointerType()) {
7645 // Member pointers are far easier, since the pointee can't be converted.
7646 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
7647 return;
7648 } else if (Ty->isEnumeralType()) {
7649 HasArithmeticOrEnumeralTypes = true;
7650 EnumerationTypes.insert(Ty);
7651 } else if (Ty->isVectorType()) {
7652 // We treat vector types as arithmetic types in many contexts as an
7653 // extension.
7654 HasArithmeticOrEnumeralTypes = true;
7655 VectorTypes.insert(Ty);
7656 } else if (Ty->isNullPtrType()) {
7657 HasNullPtrType = true;
7658 } else if (AllowUserConversions && TyRec) {
7659 // No conversion functions in incomplete types.
7660 if (!SemaRef.isCompleteType(Loc, Ty))
7661 return;
7662
7663 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7664 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7665 if (isa<UsingShadowDecl>(D))
7666 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7667
7668 // Skip conversion function templates; they don't tell us anything
7669 // about which builtin types we can convert to.
7670 if (isa<FunctionTemplateDecl>(D))
7671 continue;
7672
7673 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
7674 if (AllowExplicitConversions || !Conv->isExplicit()) {
7675 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
7676 VisibleQuals);
7677 }
7678 }
7679 }
7680}
7681/// Helper function for adjusting address spaces for the pointer or reference
7682/// operands of builtin operators depending on the argument.
7683static QualType AdjustAddressSpaceForBuiltinOperandType(Sema &S, QualType T,
7684 Expr *Arg) {
7685 return S.Context.getAddrSpaceQualType(T, Arg->getType().getAddressSpace());
7686}
7687
7688/// Helper function for AddBuiltinOperatorCandidates() that adds
7689/// the volatile- and non-volatile-qualified assignment operators for the
7690/// given type to the candidate set.
7691static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
7692 QualType T,
7693 ArrayRef<Expr *> Args,
7694 OverloadCandidateSet &CandidateSet) {
7695 QualType ParamTypes[2];
7696
7697 // T& operator=(T&, T)
7698 ParamTypes[0] = S.Context.getLValueReferenceType(
7699 AdjustAddressSpaceForBuiltinOperandType(S, T, Args[0]));
7700 ParamTypes[1] = T;
7701 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7702 /*IsAssignmentOperator=*/true);
7703
7704 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
7705 // volatile T& operator=(volatile T&, T)
7706 ParamTypes[0] = S.Context.getLValueReferenceType(
7707 AdjustAddressSpaceForBuiltinOperandType(S, S.Context.getVolatileType(T),
7708 Args[0]));
7709 ParamTypes[1] = T;
7710 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
7711 /*IsAssignmentOperator=*/true);
7712 }
7713}
7714
7715/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
7716/// if any, found in visible type conversion functions found in ArgExpr's type.
7717static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
7718 Qualifiers VRQuals;
7719 const RecordType *TyRec;
7720 if (const MemberPointerType *RHSMPType =
7721 ArgExpr->getType()->getAs<MemberPointerType>())
7722 TyRec = RHSMPType->getClass()->getAs<RecordType>();
7723 else
7724 TyRec = ArgExpr->getType()->getAs<RecordType>();
7725 if (!TyRec) {
7726 // Just to be safe, assume the worst case.
7727 VRQuals.addVolatile();
7728 VRQuals.addRestrict();
7729 return VRQuals;
7730 }
7731
7732 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
7733 if (!ClassDecl->hasDefinition())
7734 return VRQuals;
7735
7736 for (NamedDecl *D : ClassDecl->getVisibleConversionFunctions()) {
7737 if (isa<UsingShadowDecl>(D))
7738 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7739 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
7740 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
7741 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
7742 CanTy = ResTypeRef->getPointeeType();
7743 // Need to go down the pointer/mempointer chain and add qualifiers
7744 // as see them.
7745 bool done = false;
7746 while (!done) {
7747 if (CanTy.isRestrictQualified())
7748 VRQuals.addRestrict();
7749 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
7750 CanTy = ResTypePtr->getPointeeType();
7751 else if (const MemberPointerType *ResTypeMPtr =
7752 CanTy->getAs<MemberPointerType>())
7753 CanTy = ResTypeMPtr->getPointeeType();
7754 else
7755 done = true;
7756 if (CanTy.isVolatileQualified())
7757 VRQuals.addVolatile();
7758 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
7759 return VRQuals;
7760 }
7761 }
7762 }
7763 return VRQuals;
7764}
7765
7766namespace {
7767
7768/// Helper class to manage the addition of builtin operator overload
7769/// candidates. It provides shared state and utility methods used throughout
7770/// the process, as well as a helper method to add each group of builtin
7771/// operator overloads from the standard to a candidate set.
7772class BuiltinOperatorOverloadBuilder {
7773 // Common instance state available to all overload candidate addition methods.
7774 Sema &S;
7775 ArrayRef<Expr *> Args;
7776 Qualifiers VisibleTypeConversionsQuals;
7777 bool HasArithmeticOrEnumeralCandidateType;
7778 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
7779 OverloadCandidateSet &CandidateSet;
7780
7781 static constexpr int ArithmeticTypesCap = 24;
7782 SmallVector<CanQualType, ArithmeticTypesCap> ArithmeticTypes;
7783
7784 // Define some indices used to iterate over the arithemetic types in
7785 // ArithmeticTypes. The "promoted arithmetic types" are the arithmetic
7786 // types are that preserved by promotion (C++ [over.built]p2).
7787 unsigned FirstIntegralType,
7788 LastIntegralType;
7789 unsigned FirstPromotedIntegralType,
7790 LastPromotedIntegralType;
7791 unsigned FirstPromotedArithmeticType,
7792 LastPromotedArithmeticType;
7793 unsigned FirstCapabilityType,
7794 LastCapabilityType;
7795 unsigned NumArithmeticTypes;
7796
7797 void InitArithmeticTypes() {
7798 // Start of promoted types.
7799 FirstPromotedArithmeticType = 0;
7800 ArithmeticTypes.push_back(S.Context.FloatTy);
7801 ArithmeticTypes.push_back(S.Context.DoubleTy);
7802 ArithmeticTypes.push_back(S.Context.LongDoubleTy);
7803 if (S.Context.getTargetInfo().hasFloat128Type())
7804 ArithmeticTypes.push_back(S.Context.Float128Ty);
7805
7806 // Start of integral types.
7807 FirstIntegralType = ArithmeticTypes.size();
7808 FirstPromotedIntegralType = ArithmeticTypes.size();
7809 ArithmeticTypes.push_back(S.Context.IntTy);
7810 ArithmeticTypes.push_back(S.Context.LongTy);
7811 ArithmeticTypes.push_back(S.Context.LongLongTy);
7812 if (S.Context.getTargetInfo().hasInt128Type())
7813 ArithmeticTypes.push_back(S.Context.Int128Ty);
7814 ArithmeticTypes.push_back(S.Context.UnsignedIntTy);
7815 ArithmeticTypes.push_back(S.Context.UnsignedLongTy);
7816 ArithmeticTypes.push_back(S.Context.UnsignedLongLongTy);
7817 if (S.Context.getTargetInfo().hasInt128Type())
7818 ArithmeticTypes.push_back(S.Context.UnsignedInt128Ty);
7819
7820 // Capability types
7821 FirstCapabilityType = ArithmeticTypes.size();
7822 if (S.Context.getTargetInfo().SupportsCapabilities()) {
7823 ArithmeticTypes.push_back(S.Context.IntCapTy);
7824 ArithmeticTypes.push_back(S.Context.UnsignedIntCapTy);
7825 }
7826 LastCapabilityType = ArithmeticTypes.size();
7827
7828 LastPromotedIntegralType = ArithmeticTypes.size();
7829 LastPromotedArithmeticType = ArithmeticTypes.size();
7830 // End of promoted types.
7831
7832 ArithmeticTypes.push_back(S.Context.BoolTy);
7833 ArithmeticTypes.push_back(S.Context.CharTy);
7834 ArithmeticTypes.push_back(S.Context.WCharTy);
7835 if (S.Context.getLangOpts().Char8)
7836 ArithmeticTypes.push_back(S.Context.Char8Ty);
7837 ArithmeticTypes.push_back(S.Context.Char16Ty);
7838 ArithmeticTypes.push_back(S.Context.Char32Ty);
7839 ArithmeticTypes.push_back(S.Context.SignedCharTy);
7840 ArithmeticTypes.push_back(S.Context.ShortTy);
7841 ArithmeticTypes.push_back(S.Context.UnsignedCharTy);
7842 ArithmeticTypes.push_back(S.Context.UnsignedShortTy);
7843 LastIntegralType = ArithmeticTypes.size();
7844 NumArithmeticTypes = ArithmeticTypes.size();
7845 // End of integral types.
7846 // FIXME: What about complex? What about half?
7847
7848 assert(ArithmeticTypes.size() <= ArithmeticTypesCap &&
7849 "Enough inline storage for all arithmetic types.");
7850 }
7851
7852 /// Helper method to factor out the common pattern of adding overloads
7853 /// for '++' and '--' builtin operators.
7854 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
7855 bool HasVolatile,
7856 bool HasRestrict) {
7857 QualType ParamTypes[2] = {
7858 S.Context.getLValueReferenceType(CandidateTy),
7859 S.Context.IntTy
7860 };
7861
7862 // Non-volatile version.
7863 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7864
7865 // Use a heuristic to reduce number of builtin candidates in the set:
7866 // add volatile version only if there are conversions to a volatile type.
7867 if (HasVolatile) {
7868 ParamTypes[0] =
7869 S.Context.getLValueReferenceType(
7870 S.Context.getVolatileType(CandidateTy));
7871 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7872 }
7873
7874 // Add restrict version only if there are conversions to a restrict type
7875 // and our candidate type is a non-restrict-qualified pointer.
7876 if (HasRestrict && CandidateTy->isAnyPointerType() &&
7877 !CandidateTy.isRestrictQualified()) {
7878 ParamTypes[0]
7879 = S.Context.getLValueReferenceType(
7880 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
7881 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7882
7883 if (HasVolatile) {
7884 ParamTypes[0]
7885 = S.Context.getLValueReferenceType(
7886 S.Context.getCVRQualifiedType(CandidateTy,
7887 (Qualifiers::Volatile |
7888 Qualifiers::Restrict)));
7889 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
7890 }
7891 }
7892
7893 }
7894
7895public:
7896 BuiltinOperatorOverloadBuilder(
7897 Sema &S, ArrayRef<Expr *> Args,
7898 Qualifiers VisibleTypeConversionsQuals,
7899 bool HasArithmeticOrEnumeralCandidateType,
7900 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
7901 OverloadCandidateSet &CandidateSet)
7902 : S(S), Args(Args),
7903 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
7904 HasArithmeticOrEnumeralCandidateType(
7905 HasArithmeticOrEnumeralCandidateType),
7906 CandidateTypes(CandidateTypes),
7907 CandidateSet(CandidateSet) {
7908
7909 InitArithmeticTypes();
7910 }
7911
7912 // Increment is deprecated for bool since C++17.
7913 //
7914 // C++ [over.built]p3:
7915 //
7916 // For every pair (T, VQ), where T is an arithmetic type other
7917 // than bool, and VQ is either volatile or empty, there exist
7918 // candidate operator functions of the form
7919 //
7920 // VQ T& operator++(VQ T&);
7921 // T operator++(VQ T&, int);
7922 //
7923 // C++ [over.built]p4:
7924 //
7925 // For every pair (T, VQ), where T is an arithmetic type other
7926 // than bool, and VQ is either volatile or empty, there exist
7927 // candidate operator functions of the form
7928 //
7929 // VQ T& operator--(VQ T&);
7930 // T operator--(VQ T&, int);
7931 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
7932 if (!HasArithmeticOrEnumeralCandidateType)
7933 return;
7934
7935 for (unsigned Arith = 0; Arith < NumArithmeticTypes; ++Arith) {
7936 const auto TypeOfT = ArithmeticTypes[Arith];
7937 if (TypeOfT == S.Context.BoolTy) {
7938 if (Op == OO_MinusMinus)
7939 continue;
7940 if (Op == OO_PlusPlus && S.getLangOpts().CPlusPlus17)
7941 continue;
7942 }
7943 addPlusPlusMinusMinusStyleOverloads(
7944 TypeOfT,
7945 VisibleTypeConversionsQuals.hasVolatile(),
7946 VisibleTypeConversionsQuals.hasRestrict());
7947 }
7948 }
7949
7950 // C++ [over.built]p5:
7951 //
7952 // For every pair (T, VQ), where T is a cv-qualified or
7953 // cv-unqualified object type, and VQ is either volatile or
7954 // empty, there exist candidate operator functions of the form
7955 //
7956 // T*VQ& operator++(T*VQ&);
7957 // T*VQ& operator--(T*VQ&);
7958 // T* operator++(T*VQ&, int);
7959 // T* operator--(T*VQ&, int);
7960 void addPlusPlusMinusMinusPointerOverloads() {
7961 for (BuiltinCandidateTypeSet::iterator
7962 Ptr = CandidateTypes[0].pointer_begin(),
7963 PtrEnd = CandidateTypes[0].pointer_end();
7964 Ptr != PtrEnd; ++Ptr) {
7965 // Skip pointer types that aren't pointers to object types.
7966 if (!(*Ptr)->getPointeeType()->isObjectType())
7967 continue;
7968
7969 addPlusPlusMinusMinusStyleOverloads(*Ptr,
7970 (!(*Ptr).isVolatileQualified() &&
7971 VisibleTypeConversionsQuals.hasVolatile()),
7972 (!(*Ptr).isRestrictQualified() &&
7973 VisibleTypeConversionsQuals.hasRestrict()));
7974 }
7975 }
7976
7977 // C++ [over.built]p6:
7978 // For every cv-qualified or cv-unqualified object type T, there
7979 // exist candidate operator functions of the form
7980 //
7981 // T& operator*(T*);
7982 //
7983 // C++ [over.built]p7:
7984 // For every function type T that does not have cv-qualifiers or a
7985 // ref-qualifier, there exist candidate operator functions of the form
7986 // T& operator*(T*);
7987 void addUnaryStarPointerOverloads() {
7988 for (BuiltinCandidateTypeSet::iterator
7989 Ptr = CandidateTypes[0].pointer_begin(),
7990 PtrEnd = CandidateTypes[0].pointer_end();
7991 Ptr != PtrEnd; ++Ptr) {
7992 QualType ParamTy = *Ptr;
7993 QualType PointeeTy = ParamTy->getPointeeType();
7994 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7995 continue;
7996
7997 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7998 if (Proto->getMethodQuals() || Proto->getRefQualifier())
7999 continue;
8000
8001 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8002 }
8003 }
8004
8005 // C++ [over.built]p9:
8006 // For every promoted arithmetic type T, there exist candidate
8007 // operator functions of the form
8008 //
8009 // T operator+(T);
8010 // T operator-(T);
8011 void addUnaryPlusOrMinusArithmeticOverloads() {
8012 if (!HasArithmeticOrEnumeralCandidateType)
8013 return;
8014
8015 for (unsigned Arith = FirstPromotedArithmeticType;
8016 Arith < LastPromotedArithmeticType; ++Arith) {
8017 QualType ArithTy = ArithmeticTypes[Arith];
8018 S.AddBuiltinCandidate(&ArithTy, Args, CandidateSet);
8019 }
8020
8021 // Extension: We also add these operators for vector types.
8022 for (BuiltinCandidateTypeSet::iterator
8023 Vec = CandidateTypes[0].vector_begin(),
8024 VecEnd = CandidateTypes[0].vector_end();
8025 Vec != VecEnd; ++Vec) {
8026 QualType VecTy = *Vec;
8027 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8028 }
8029 }
8030
8031 // C++ [over.built]p8:
8032 // For every type T, there exist candidate operator functions of
8033 // the form
8034 //
8035 // T* operator+(T*);
8036 void addUnaryPlusPointerOverloads() {
8037 for (BuiltinCandidateTypeSet::iterator
8038 Ptr = CandidateTypes[0].pointer_begin(),
8039 PtrEnd = CandidateTypes[0].pointer_end();
8040 Ptr != PtrEnd; ++Ptr) {
8041 QualType ParamTy = *Ptr;
8042 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet);
8043 }
8044 }
8045
8046 // C++ [over.built]p10:
8047 // For every promoted integral type T, there exist candidate
8048 // operator functions of the form
8049 //
8050 // T operator~(T);
8051 void addUnaryTildePromotedIntegralOverloads() {
8052 if (!HasArithmeticOrEnumeralCandidateType)
8053 return;
8054
8055 for (unsigned Int = FirstPromotedIntegralType;
8056 Int < LastPromotedIntegralType; ++Int) {
8057 QualType IntTy = ArithmeticTypes[Int];
8058 S.AddBuiltinCandidate(&IntTy, Args, CandidateSet);
8059 }
8060
8061 // Extension: We also add this operator for vector types.
8062 for (BuiltinCandidateTypeSet::iterator
8063 Vec = CandidateTypes[0].vector_begin(),
8064 VecEnd = CandidateTypes[0].vector_end();
8065 Vec != VecEnd; ++Vec) {
8066 QualType VecTy = *Vec;
8067 S.AddBuiltinCandidate(&VecTy, Args, CandidateSet);
8068 }
8069 }
8070
8071 // C++ [over.match.oper]p16:
8072 // For every pointer to member type T or type std::nullptr_t, there
8073 // exist candidate operator functions of the form
8074 //
8075 // bool operator==(T,T);
8076 // bool operator!=(T,T);
8077 void addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads() {
8078 /// Set of (canonical) types that we've already handled.
8079 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8080
8081 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8082 for (BuiltinCandidateTypeSet::iterator
8083 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8084 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8085 MemPtr != MemPtrEnd;
8086 ++MemPtr) {
8087 // Don't add the same builtin candidate twice.
8088 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8089 continue;
8090
8091 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8092 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8093 }
8094
8095 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
8096 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
8097 if (AddedTypes.insert(NullPtrTy).second) {
8098 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
8099 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8100 }
8101 }
8102 }
8103 }
8104
8105 // C++ [over.built]p15:
8106 //
8107 // For every T, where T is an enumeration type or a pointer type,
8108 // there exist candidate operator functions of the form
8109 //
8110 // bool operator<(T, T);
8111 // bool operator>(T, T);
8112 // bool operator<=(T, T);
8113 // bool operator>=(T, T);
8114 // bool operator==(T, T);
8115 // bool operator!=(T, T);
8116 // R operator<=>(T, T)
8117 void addGenericBinaryPointerOrEnumeralOverloads() {
8118 // C++ [over.match.oper]p3:
8119 // [...]the built-in candidates include all of the candidate operator
8120 // functions defined in 13.6 that, compared to the given operator, [...]
8121 // do not have the same parameter-type-list as any non-template non-member
8122 // candidate.
8123 //
8124 // Note that in practice, this only affects enumeration types because there
8125 // aren't any built-in candidates of record type, and a user-defined operator
8126 // must have an operand of record or enumeration type. Also, the only other
8127 // overloaded operator with enumeration arguments, operator=,
8128 // cannot be overloaded for enumeration types, so this is the only place
8129 // where we must suppress candidates like this.
8130 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
8131 UserDefinedBinaryOperators;
8132
8133 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8134 if (CandidateTypes[ArgIdx].enumeration_begin() !=
8135 CandidateTypes[ArgIdx].enumeration_end()) {
8136 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
8137 CEnd = CandidateSet.end();
8138 C != CEnd; ++C) {
8139 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
8140 continue;
8141
8142 if (C->Function->isFunctionTemplateSpecialization())
8143 continue;
8144
8145 QualType FirstParamType =
8146 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
8147 QualType SecondParamType =
8148 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
8149
8150 // Skip if either parameter isn't of enumeral type.
8151 if (!FirstParamType->isEnumeralType() ||
8152 !SecondParamType->isEnumeralType())
8153 continue;
8154
8155 // Add this operator to the set of known user-defined operators.
8156 UserDefinedBinaryOperators.insert(
8157 std::make_pair(S.Context.getCanonicalType(FirstParamType),
8158 S.Context.getCanonicalType(SecondParamType)));
8159 }
8160 }
8161 }
8162
8163 /// Set of (canonical) types that we've already handled.
8164 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8165
8166 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8167 for (BuiltinCandidateTypeSet::iterator
8168 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8169 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8170 Ptr != PtrEnd; ++Ptr) {
8171 // Don't add the same builtin candidate twice.
8172 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8173 continue;
8174
8175 QualType ParamTypes[2] = { *Ptr, *Ptr };
8176 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8177 }
8178 for (BuiltinCandidateTypeSet::iterator
8179 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8180 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8181 Enum != EnumEnd; ++Enum) {
8182 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
8183
8184 // Don't add the same builtin candidate twice, or if a user defined
8185 // candidate exists.
8186 if (!AddedTypes.insert(CanonType).second ||
8187 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
8188 CanonType)))
8189 continue;
8190 QualType ParamTypes[2] = { *Enum, *Enum };
8191 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8192 }
8193 }
8194 }
8195
8196 // C++ [over.built]p13:
8197 //
8198 // For every cv-qualified or cv-unqualified object type T
8199 // there exist candidate operator functions of the form
8200 //
8201 // T* operator+(T*, ptrdiff_t);
8202 // T& operator[](T*, ptrdiff_t); [BELOW]
8203 // T* operator-(T*, ptrdiff_t);
8204 // T* operator+(ptrdiff_t, T*);
8205 // T& operator[](ptrdiff_t, T*); [BELOW]
8206 //
8207 // C++ [over.built]p14:
8208 //
8209 // For every T, where T is a pointer to object type, there
8210 // exist candidate operator functions of the form
8211 //
8212 // ptrdiff_t operator-(T, T);
8213 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
8214 /// Set of (canonical) types that we've already handled.
8215 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8216
8217 for (int Arg = 0; Arg < 2; ++Arg) {
8218 QualType AsymmetricParamTypes[2] = {
8219 S.Context.getPointerDiffType(),
8220 S.Context.getPointerDiffType(),
8221 };
8222 for (BuiltinCandidateTypeSet::iterator
8223 Ptr = CandidateTypes[Arg].pointer_begin(),
8224 PtrEnd = CandidateTypes[Arg].pointer_end();
8225 Ptr != PtrEnd; ++Ptr) {
8226 QualType PointeeTy = (*Ptr)->getPointeeType();
8227 if (!PointeeTy->isObjectType())
8228 continue;
8229
8230 AsymmetricParamTypes[Arg] = *Ptr;
8231 if (Arg == 0 || Op == OO_Plus) {
8232 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
8233 // T* operator+(ptrdiff_t, T*);
8234 S.AddBuiltinCandidate(AsymmetricParamTypes, Args, CandidateSet);
8235 }
8236 if (Op == OO_Minus) {
8237 // ptrdiff_t operator-(T, T);
8238 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8239 continue;
8240
8241 QualType ParamTypes[2] = { *Ptr, *Ptr };
8242 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8243 }
8244 }
8245 }
8246 }
8247
8248 // C++ [over.built]p12:
8249 //
8250 // For every pair of promoted arithmetic types L and R, there
8251 // exist candidate operator functions of the form
8252 //
8253 // LR operator*(L, R);
8254 // LR operator/(L, R);
8255 // LR operator+(L, R);
8256 // LR operator-(L, R);
8257 // bool operator<(L, R);
8258 // bool operator>(L, R);
8259 // bool operator<=(L, R);
8260 // bool operator>=(L, R);
8261 // bool operator==(L, R);
8262 // bool operator!=(L, R);
8263 //
8264 // where LR is the result of the usual arithmetic conversions
8265 // between types L and R.
8266 //
8267 // C++ [over.built]p24:
8268 //
8269 // For every pair of promoted arithmetic types L and R, there exist
8270 // candidate operator functions of the form
8271 //
8272 // LR operator?(bool, L, R);
8273 //
8274 // where LR is the result of the usual arithmetic conversions
8275 // between types L and R.
8276 // Our candidates ignore the first parameter.
8277 void addGenericBinaryArithmeticOverloads() {
8278 if (!HasArithmeticOrEnumeralCandidateType)
8279 return;
8280 for (unsigned Left = FirstPromotedArithmeticType;
8281 Left < LastPromotedArithmeticType; ++Left) {
8282 for (unsigned Right = FirstPromotedArithmeticType;
8283 Right < LastPromotedArithmeticType; ++Right) {
8284 QualType LandR[2] = { ArithmeticTypes[Left],
8285 ArithmeticTypes[Right] };
8286 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8287 }
8288 }
8289
8290 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
8291 // conditional operator for vector types.
8292 for (BuiltinCandidateTypeSet::iterator
8293 Vec1 = CandidateTypes[0].vector_begin(),
8294 Vec1End = CandidateTypes[0].vector_end();
8295 Vec1 != Vec1End; ++Vec1) {
8296 for (BuiltinCandidateTypeSet::iterator
8297 Vec2 = CandidateTypes[1].vector_begin(),
8298 Vec2End = CandidateTypes[1].vector_end();
8299 Vec2 != Vec2End; ++Vec2) {
8300 QualType LandR[2] = { *Vec1, *Vec2 };
8301 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8302 }
8303 }
8304 }
8305
8306 // C++2a [over.built]p14:
8307 //
8308 // For every integral type T there exists a candidate operator function
8309 // of the form
8310 //
8311 // std::strong_ordering operator<=>(T, T)
8312 //
8313 // C++2a [over.built]p15:
8314 //
8315 // For every pair of floating-point types L and R, there exists a candidate
8316 // operator function of the form
8317 //
8318 // std::partial_ordering operator<=>(L, R);
8319 //
8320 // FIXME: The current specification for integral types doesn't play nice with
8321 // the direction of p0946r0, which allows mixed integral and unscoped-enum
8322 // comparisons. Under the current spec this can lead to ambiguity during
8323 // overload resolution. For example:
8324 //
8325 // enum A : int {a};
8326 // auto x = (a <=> (long)42);
8327 //
8328 // error: call is ambiguous for arguments 'A' and 'long'.
8329 // note: candidate operator<=>(int, int)
8330 // note: candidate operator<=>(long, long)
8331 //
8332 // To avoid this error, this function deviates from the specification and adds
8333 // the mixed overloads `operator<=>(L, R)` where L and R are promoted
8334 // arithmetic types (the same as the generic relational overloads).
8335 //
8336 // For now this function acts as a placeholder.
8337 void addThreeWayArithmeticOverloads() {
8338 addGenericBinaryArithmeticOverloads();
8339 }
8340
8341 // C++ [over.built]p17:
8342 //
8343 // For every pair of promoted integral types L and R, there
8344 // exist candidate operator functions of the form
8345 //
8346 // LR operator%(L, R);
8347 // LR operator&(L, R);
8348 // LR operator^(L, R);
8349 // LR operator|(L, R);
8350 // L operator<<(L, R);
8351 // L operator>>(L, R);
8352 //
8353 // where LR is the result of the usual arithmetic conversions
8354 // between types L and R.
8355 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
8356 if (!HasArithmeticOrEnumeralCandidateType)
8357 return;
8358
8359 unsigned LastType = S.Context.getTargetInfo().SupportsCapabilities()
8360 ? LastCapabilityType : LastPromotedIntegralType;
8361 // XXXAR: allow any type as the RHS operand for a bitwise op with capabilities
8362 for (unsigned Left = FirstPromotedIntegralType;
8363 Left < LastType; ++Left) {
8364 for (unsigned Right = FirstPromotedIntegralType;
8365 Right < LastPromotedIntegralType; ++Right) {
8366 QualType LandR[2] = { ArithmeticTypes[Left],
8367 ArithmeticTypes[Right] };
8368 S.AddBuiltinCandidate(LandR, Args, CandidateSet);
8369 }
8370 }
8371
8372 }
8373
8374 // C++ [over.built]p20:
8375 //
8376 // For every pair (T, VQ), where T is an enumeration or
8377 // pointer to member type and VQ is either volatile or
8378 // empty, there exist candidate operator functions of the form
8379 //
8380 // VQ T& operator=(VQ T&, T);
8381 void addAssignmentMemberPointerOrEnumeralOverloads() {
8382 /// Set of (canonical) types that we've already handled.
8383 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8384
8385 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8386 for (BuiltinCandidateTypeSet::iterator
8387 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8388 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8389 Enum != EnumEnd; ++Enum) {
8390 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8391 continue;
8392
8393 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
8394 }
8395
8396 for (BuiltinCandidateTypeSet::iterator
8397 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8398 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8399 MemPtr != MemPtrEnd; ++MemPtr) {
8400 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8401 continue;
8402
8403 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
8404 }
8405 }
8406 }
8407
8408 // C++ [over.built]p19:
8409 //
8410 // For every pair (T, VQ), where T is any type and VQ is either
8411 // volatile or empty, there exist candidate operator functions
8412 // of the form
8413 //
8414 // T*VQ& operator=(T*VQ&, T*);
8415 //
8416 // C++ [over.built]p21:
8417 //
8418 // For every pair (T, VQ), where T is a cv-qualified or
8419 // cv-unqualified object type and VQ is either volatile or
8420 // empty, there exist candidate operator functions of the form
8421 //
8422 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
8423 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
8424 void addAssignmentPointerOverloads(bool isEqualOp) {
8425 /// Set of (canonical) types that we've already handled.
8426 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8427
8428 for (BuiltinCandidateTypeSet::iterator
8429 Ptr = CandidateTypes[0].pointer_begin(),
8430 PtrEnd = CandidateTypes[0].pointer_end();
8431 Ptr != PtrEnd; ++Ptr) {
8432 // If this is operator=, keep track of the builtin candidates we added.
8433 if (isEqualOp)
8434 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
8435 else if (!(*Ptr)->getPointeeType()->isObjectType())
8436 continue;
8437
8438 // non-volatile version
8439 QualType ParamTypes[2] = {
8440 S.Context.getLValueReferenceType(*Ptr),
8441 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
8442 };
8443 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8444 /*IsAssigmentOperator=*/ isEqualOp);
8445
8446 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8447 VisibleTypeConversionsQuals.hasVolatile();
8448 if (NeedVolatile) {
8449 // volatile version
8450 ParamTypes[0] =
8451 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8452 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8453 /*IsAssigmentOperator=*/isEqualOp);
8454 }
8455
8456 if (!(*Ptr).isRestrictQualified() &&
8457 VisibleTypeConversionsQuals.hasRestrict()) {
8458 // restrict version
8459 ParamTypes[0]
8460 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8461 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8462 /*IsAssigmentOperator=*/isEqualOp);
8463
8464 if (NeedVolatile) {
8465 // volatile restrict version
8466 ParamTypes[0]
8467 = S.Context.getLValueReferenceType(
8468 S.Context.getCVRQualifiedType(*Ptr,
8469 (Qualifiers::Volatile |
8470 Qualifiers::Restrict)));
8471 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8472 /*IsAssigmentOperator=*/isEqualOp);
8473 }
8474 }
8475 }
8476
8477 if (isEqualOp) {
8478 for (BuiltinCandidateTypeSet::iterator
8479 Ptr = CandidateTypes[1].pointer_begin(),
8480 PtrEnd = CandidateTypes[1].pointer_end();
8481 Ptr != PtrEnd; ++Ptr) {
8482 // Make sure we don't add the same candidate twice.
8483 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8484 continue;
8485
8486 QualType ParamTypes[2] = {
8487 S.Context.getLValueReferenceType(*Ptr),
8488 *Ptr,
8489 };
8490
8491 // non-volatile version
8492 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8493 /*IsAssigmentOperator=*/true);
8494
8495 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
8496 VisibleTypeConversionsQuals.hasVolatile();
8497 if (NeedVolatile) {
8498 // volatile version
8499 ParamTypes[0] =
8500 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
8501 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8502 /*IsAssigmentOperator=*/true);
8503 }
8504
8505 if (!(*Ptr).isRestrictQualified() &&
8506 VisibleTypeConversionsQuals.hasRestrict()) {
8507 // restrict version
8508 ParamTypes[0]
8509 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
8510 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8511 /*IsAssigmentOperator=*/true);
8512
8513 if (NeedVolatile) {
8514 // volatile restrict version
8515 ParamTypes[0]
8516 = S.Context.getLValueReferenceType(
8517 S.Context.getCVRQualifiedType(*Ptr,
8518 (Qualifiers::Volatile |
8519 Qualifiers::Restrict)));
8520 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8521 /*IsAssigmentOperator=*/true);
8522 }
8523 }
8524 }
8525 }
8526 }
8527
8528 // C++ [over.built]p18:
8529 //
8530 // For every triple (L, VQ, R), where L is an arithmetic type,
8531 // VQ is either volatile or empty, and R is a promoted
8532 // arithmetic type, there exist candidate operator functions of
8533 // the form
8534 //
8535 // VQ L& operator=(VQ L&, R);
8536 // VQ L& operator*=(VQ L&, R);
8537 // VQ L& operator/=(VQ L&, R);
8538 // VQ L& operator+=(VQ L&, R);
8539 // VQ L& operator-=(VQ L&, R);
8540 void addAssignmentArithmeticOverloads(bool isEqualOp) {
8541 if (!HasArithmeticOrEnumeralCandidateType)
8542 return;
8543
8544 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
8545 for (unsigned Right = FirstPromotedArithmeticType;
8546 Right < LastPromotedArithmeticType; ++Right) {
8547 QualType ParamTypes[2];
8548 ParamTypes[1] = ArithmeticTypes[Right];
8549 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8550 S, ArithmeticTypes[Left], Args[0]);
8551 // Add this built-in operator as a candidate (VQ is empty).
8552 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8553 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8554 /*IsAssigmentOperator=*/isEqualOp);
8555
8556 // Add this built-in operator as a candidate (VQ is 'volatile').
8557 if (VisibleTypeConversionsQuals.hasVolatile()) {
8558 ParamTypes[0] = S.Context.getVolatileType(LeftBaseTy);
8559 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8560 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8561 /*IsAssigmentOperator=*/isEqualOp);
8562 }
8563 }
8564 }
8565
8566 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
8567 for (BuiltinCandidateTypeSet::iterator
8568 Vec1 = CandidateTypes[0].vector_begin(),
8569 Vec1End = CandidateTypes[0].vector_end();
8570 Vec1 != Vec1End; ++Vec1) {
8571 for (BuiltinCandidateTypeSet::iterator
8572 Vec2 = CandidateTypes[1].vector_begin(),
8573 Vec2End = CandidateTypes[1].vector_end();
8574 Vec2 != Vec2End; ++Vec2) {
8575 QualType ParamTypes[2];
8576 ParamTypes[1] = *Vec2;
8577 // Add this built-in operator as a candidate (VQ is empty).
8578 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
8579 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8580 /*IsAssigmentOperator=*/isEqualOp);
8581
8582 // Add this built-in operator as a candidate (VQ is 'volatile').
8583 if (VisibleTypeConversionsQuals.hasVolatile()) {
8584 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
8585 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8586 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8587 /*IsAssigmentOperator=*/isEqualOp);
8588 }
8589 }
8590 }
8591 }
8592
8593 // C++ [over.built]p22:
8594 //
8595 // For every triple (L, VQ, R), where L is an integral type, VQ
8596 // is either volatile or empty, and R is a promoted integral
8597 // type, there exist candidate operator functions of the form
8598 //
8599 // VQ L& operator%=(VQ L&, R);
8600 // VQ L& operator<<=(VQ L&, R);
8601 // VQ L& operator>>=(VQ L&, R);
8602 // VQ L& operator&=(VQ L&, R);
8603 // VQ L& operator^=(VQ L&, R);
8604 // VQ L& operator|=(VQ L&, R);
8605 void addAssignmentIntegralOverloads() {
8606 if (!HasArithmeticOrEnumeralCandidateType)
8607 return;
8608
8609 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
8610 for (unsigned Right = FirstPromotedIntegralType;
8611 Right < LastPromotedIntegralType; ++Right) {
8612 QualType ParamTypes[2];
8613 ParamTypes[1] = ArithmeticTypes[Right];
8614 auto LeftBaseTy = AdjustAddressSpaceForBuiltinOperandType(
8615 S, ArithmeticTypes[Left], Args[0]);
8616 // Add this built-in operator as a candidate (VQ is empty).
8617 ParamTypes[0] = S.Context.getLValueReferenceType(LeftBaseTy);
8618 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8619 if (VisibleTypeConversionsQuals.hasVolatile()) {
8620 // Add this built-in operator as a candidate (VQ is 'volatile').
8621 ParamTypes[0] = LeftBaseTy;
8622 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
8623 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
8624 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8625 }
8626 }
8627 }
8628 }
8629
8630 // C++ [over.operator]p23:
8631 //
8632 // There also exist candidate operator functions of the form
8633 //
8634 // bool operator!(bool);
8635 // bool operator&&(bool, bool);
8636 // bool operator||(bool, bool);
8637 void addExclaimOverload() {
8638 QualType ParamTy = S.Context.BoolTy;
8639 S.AddBuiltinCandidate(&ParamTy, Args, CandidateSet,
8640 /*IsAssignmentOperator=*/false,
8641 /*NumContextualBoolArguments=*/1);
8642 }
8643 void addAmpAmpOrPipePipeOverload() {
8644 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
8645 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet,
8646 /*IsAssignmentOperator=*/false,
8647 /*NumContextualBoolArguments=*/2);
8648 }
8649
8650 // C++ [over.built]p13:
8651 //
8652 // For every cv-qualified or cv-unqualified object type T there
8653 // exist candidate operator functions of the form
8654 //
8655 // T* operator+(T*, ptrdiff_t); [ABOVE]
8656 // T& operator[](T*, ptrdiff_t);
8657 // T* operator-(T*, ptrdiff_t); [ABOVE]
8658 // T* operator+(ptrdiff_t, T*); [ABOVE]
8659 // T& operator[](ptrdiff_t, T*);
8660 void addSubscriptOverloads() {
8661 for (BuiltinCandidateTypeSet::iterator
8662 Ptr = CandidateTypes[0].pointer_begin(),
8663 PtrEnd = CandidateTypes[0].pointer_end();
8664 Ptr != PtrEnd; ++Ptr) {
8665 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
8666 QualType PointeeType = (*Ptr)->getPointeeType();
8667 if (!PointeeType->isObjectType())
8668 continue;
8669
8670 // T& operator[](T*, ptrdiff_t)
8671 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8672 }
8673
8674 for (BuiltinCandidateTypeSet::iterator
8675 Ptr = CandidateTypes[1].pointer_begin(),
8676 PtrEnd = CandidateTypes[1].pointer_end();
8677 Ptr != PtrEnd; ++Ptr) {
8678 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
8679 QualType PointeeType = (*Ptr)->getPointeeType();
8680 if (!PointeeType->isObjectType())
8681 continue;
8682
8683 // T& operator[](ptrdiff_t, T*)
8684 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8685 }
8686 }
8687
8688 // C++ [over.built]p11:
8689 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
8690 // C1 is the same type as C2 or is a derived class of C2, T is an object
8691 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
8692 // there exist candidate operator functions of the form
8693 //
8694 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
8695 //
8696 // where CV12 is the union of CV1 and CV2.
8697 void addArrowStarOverloads() {
8698 for (BuiltinCandidateTypeSet::iterator
8699 Ptr = CandidateTypes[0].pointer_begin(),
8700 PtrEnd = CandidateTypes[0].pointer_end();
8701 Ptr != PtrEnd; ++Ptr) {
8702 QualType C1Ty = (*Ptr);
8703 QualType C1;
8704 QualifierCollector Q1;
8705 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
8706 if (!isa<RecordType>(C1))
8707 continue;
8708 // heuristic to reduce number of builtin candidates in the set.
8709 // Add volatile/restrict version only if there are conversions to a
8710 // volatile/restrict type.
8711 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
8712 continue;
8713 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
8714 continue;
8715 for (BuiltinCandidateTypeSet::iterator
8716 MemPtr = CandidateTypes[1].member_pointer_begin(),
8717 MemPtrEnd = CandidateTypes[1].member_pointer_end();
8718 MemPtr != MemPtrEnd; ++MemPtr) {
8719 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
8720 QualType C2 = QualType(mptr->getClass(), 0);
8721 C2 = C2.getUnqualifiedType();
8722 if (C1 != C2 && !S.IsDerivedFrom(CandidateSet.getLocation(), C1, C2))
8723 break;
8724 QualType ParamTypes[2] = { *Ptr, *MemPtr };
8725 // build CV12 T&
8726 QualType T = mptr->getPointeeType();
8727 if (!VisibleTypeConversionsQuals.hasVolatile() &&
8728 T.isVolatileQualified())
8729 continue;
8730 if (!VisibleTypeConversionsQuals.hasRestrict() &&
8731 T.isRestrictQualified())
8732 continue;
8733 T = Q1.apply(S.Context, T);
8734 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8735 }
8736 }
8737 }
8738
8739 // Note that we don't consider the first argument, since it has been
8740 // contextually converted to bool long ago. The candidates below are
8741 // therefore added as binary.
8742 //
8743 // C++ [over.built]p25:
8744 // For every type T, where T is a pointer, pointer-to-member, or scoped
8745 // enumeration type, there exist candidate operator functions of the form
8746 //
8747 // T operator?(bool, T, T);
8748 //
8749 void addConditionalOperatorOverloads() {
8750 /// Set of (canonical) types that we've already handled.
8751 llvm::SmallPtrSet<QualType, 8> AddedTypes;
8752
8753 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
8754 for (BuiltinCandidateTypeSet::iterator
8755 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
8756 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
8757 Ptr != PtrEnd; ++Ptr) {
8758 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)).second)
8759 continue;
8760
8761 QualType ParamTypes[2] = { *Ptr, *Ptr };
8762 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8763 }
8764
8765 for (BuiltinCandidateTypeSet::iterator
8766 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
8767 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
8768 MemPtr != MemPtrEnd; ++MemPtr) {
8769 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)).second)
8770 continue;
8771
8772 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
8773 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8774 }
8775
8776 if (S.getLangOpts().CPlusPlus11) {
8777 for (BuiltinCandidateTypeSet::iterator
8778 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
8779 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
8780 Enum != EnumEnd; ++Enum) {
8781 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
8782 continue;
8783
8784 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)).second)
8785 continue;
8786
8787 QualType ParamTypes[2] = { *Enum, *Enum };
8788 S.AddBuiltinCandidate(ParamTypes, Args, CandidateSet);
8789 }
8790 }
8791 }
8792 }
8793};
8794
8795} // end anonymous namespace
8796
8797/// AddBuiltinOperatorCandidates - Add the appropriate built-in
8798/// operator overloads to the candidate set (C++ [over.built]), based
8799/// on the operator @p Op and the arguments given. For example, if the
8800/// operator is a binary '+', this routine might add "int
8801/// operator+(int, int)" to cover integer addition.
8802void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
8803 SourceLocation OpLoc,
8804 ArrayRef<Expr *> Args,
8805 OverloadCandidateSet &CandidateSet) {
8806 // Find all of the types that the arguments can convert to, but only
8807 // if the operator we're looking at has built-in operator candidates
8808 // that make use of these types. Also record whether we encounter non-record
8809 // candidate types or either arithmetic or enumeral candidate types.
8810 Qualifiers VisibleTypeConversionsQuals;
8811 VisibleTypeConversionsQuals.addConst();
8812 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
8813 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
8814
8815 bool HasNonRecordCandidateType = false;
8816 bool HasArithmeticOrEnumeralCandidateType = false;
8817 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
8818 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
8819 CandidateTypes.emplace_back(*this);
8820 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
8821 OpLoc,
8822 true,
8823 (Op == OO_Exclaim ||
8824 Op == OO_AmpAmp ||
8825 Op == OO_PipePipe),
8826 VisibleTypeConversionsQuals);
8827 HasNonRecordCandidateType = HasNonRecordCandidateType ||
8828 CandidateTypes[ArgIdx].hasNonRecordTypes();
8829 HasArithmeticOrEnumeralCandidateType =
8830 HasArithmeticOrEnumeralCandidateType ||
8831 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
8832 }
8833
8834 // Exit early when no non-record types have been added to the candidate set
8835 // for any of the arguments to the operator.
8836 //
8837 // We can't exit early for !, ||, or &&, since there we have always have
8838 // 'bool' overloads.
8839 if (!HasNonRecordCandidateType &&
8840 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
8841 return;
8842
8843 // Setup an object to manage the common state for building overloads.
8844 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
8845 VisibleTypeConversionsQuals,
8846 HasArithmeticOrEnumeralCandidateType,
8847 CandidateTypes, CandidateSet);
8848
8849 // Dispatch over the operation to add in only those overloads which apply.
8850 switch (Op) {
8851 case OO_None:
8852 case NUM_OVERLOADED_OPERATORS:
8853 llvm_unreachable("Expected an overloaded operator");
8854
8855 case OO_New:
8856 case OO_Delete:
8857 case OO_Array_New:
8858 case OO_Array_Delete:
8859 case OO_Call:
8860 llvm_unreachable(
8861 "Special operators don't use AddBuiltinOperatorCandidates");
8862
8863 case OO_Comma:
8864 case OO_Arrow:
8865 case OO_Coawait:
8866 // C++ [over.match.oper]p3:
8867 // -- For the operator ',', the unary operator '&', the
8868 // operator '->', or the operator 'co_await', the
8869 // built-in candidates set is empty.
8870 break;
8871
8872 case OO_Plus: // '+' is either unary or binary
8873 if (Args.size() == 1)
8874 OpBuilder.addUnaryPlusPointerOverloads();
8875 LLVM_FALLTHROUGH;
8876
8877 case OO_Minus: // '-' is either unary or binary
8878 if (Args.size() == 1) {
8879 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
8880 } else {
8881 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
8882 OpBuilder.addGenericBinaryArithmeticOverloads();
8883 }
8884 break;
8885
8886 case OO_Star: // '*' is either unary or binary
8887 if (Args.size() == 1)
8888 OpBuilder.addUnaryStarPointerOverloads();
8889 else
8890 OpBuilder.addGenericBinaryArithmeticOverloads();
8891 break;
8892
8893 case OO_Slash:
8894 OpBuilder.addGenericBinaryArithmeticOverloads();
8895 break;
8896
8897 case OO_PlusPlus:
8898 case OO_MinusMinus:
8899 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8900 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
8901 break;
8902
8903 case OO_EqualEqual:
8904 case OO_ExclaimEqual:
8905 OpBuilder.addEqualEqualOrNotEqualMemberPointerOrNullptrOverloads();
8906 LLVM_FALLTHROUGH;
8907
8908 case OO_Less:
8909 case OO_Greater:
8910 case OO_LessEqual:
8911 case OO_GreaterEqual:
8912 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8913 OpBuilder.addGenericBinaryArithmeticOverloads();
8914 break;
8915
8916 case OO_Spaceship:
8917 OpBuilder.addGenericBinaryPointerOrEnumeralOverloads();
8918 OpBuilder.addThreeWayArithmeticOverloads();
8919 break;
8920
8921 case OO_Percent:
8922 case OO_Caret:
8923 case OO_Pipe:
8924 case OO_LessLess:
8925 case OO_GreaterGreater:
8926 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8927 break;
8928
8929 case OO_Amp: // '&' is either unary or binary
8930 if (Args.size() == 1)
8931 // C++ [over.match.oper]p3:
8932 // -- For the operator ',', the unary operator '&', or the
8933 // operator '->', the built-in candidates set is empty.
8934 break;
8935
8936 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8937 break;
8938
8939 case OO_Tilde:
8940 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8941 break;
8942
8943 case OO_Equal:
8944 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
8945 LLVM_FALLTHROUGH;
8946
8947 case OO_PlusEqual:
8948 case OO_MinusEqual:
8949 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
8950 LLVM_FALLTHROUGH;
8951
8952 case OO_StarEqual:
8953 case OO_SlashEqual:
8954 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
8955 break;
8956
8957 case OO_PercentEqual:
8958 case OO_LessLessEqual:
8959 case OO_GreaterGreaterEqual:
8960 case OO_AmpEqual:
8961 case OO_CaretEqual:
8962 case OO_PipeEqual:
8963 OpBuilder.addAssignmentIntegralOverloads();
8964 break;
8965
8966 case OO_Exclaim:
8967 OpBuilder.addExclaimOverload();
8968 break;
8969
8970 case OO_AmpAmp:
8971 case OO_PipePipe:
8972 OpBuilder.addAmpAmpOrPipePipeOverload();
8973 break;
8974
8975 case OO_Subscript:
8976 OpBuilder.addSubscriptOverloads();
8977 break;
8978
8979 case OO_ArrowStar:
8980 OpBuilder.addArrowStarOverloads();
8981 break;
8982
8983 case OO_Conditional:
8984 OpBuilder.addConditionalOperatorOverloads();
8985 OpBuilder.addGenericBinaryArithmeticOverloads();
8986 break;
8987 }
8988}
8989
8990/// Add function candidates found via argument-dependent lookup
8991/// to the set of overloading candidates.
8992///
8993/// This routine performs argument-dependent name lookup based on the
8994/// given function name (which may also be an operator name) and adds
8995/// all of the overload candidates found by ADL to the overload
8996/// candidate set (C++ [basic.lookup.argdep]).
8997void
8998Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
8999 SourceLocation Loc,
9000 ArrayRef<Expr *> Args,
9001 TemplateArgumentListInfo *ExplicitTemplateArgs,
9002 OverloadCandidateSet& CandidateSet,
9003 bool PartialOverloading) {
9004 ADLResult Fns;
9005
9006 // FIXME: This approach for uniquing ADL results (and removing
9007 // redundant candidates from the set) relies on pointer-equality,
9008 // which means we need to key off the canonical decl. However,
9009 // always going back to the canonical decl might not get us the
9010 // right set of default arguments. What default arguments are
9011 // we supposed to consider on ADL candidates, anyway?
9012
9013 // FIXME: Pass in the explicit template arguments?
9014 ArgumentDependentLookup(Name, Loc, Args, Fns);
9015
9016 // Erase all of the candidates we already knew about.
9017 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
9018 CandEnd = CandidateSet.end();
9019 Cand != CandEnd; ++Cand)
9020 if (Cand->Function) {
9021 Fns.erase(Cand->Function);
9022 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
9023 Fns.erase(FunTmpl);
9024 }
9025
9026 // For each of the ADL candidates we found, add it to the overload
9027 // set.
9028 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
9029 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
9030
9031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
9032 if (ExplicitTemplateArgs)
9033 continue;
9034
9035 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet,
9036 /*SupressUserConversions=*/false, PartialOverloading,
9037 /*AllowExplicit*/ true,
9038 /*AllowExplicitConversions*/ false,
9039 ADLCallKind::UsesADL);
9040 } else {
9041 AddTemplateOverloadCandidate(
9042 cast<FunctionTemplateDecl>(*I), FoundDecl, ExplicitTemplateArgs, Args,
9043 CandidateSet,
9044 /*SuppressUserConversions=*/false, PartialOverloading,
9045 /*AllowExplicit*/true, ADLCallKind::UsesADL);
9046 }
9047 }
9048}
9049
9050namespace {
9051enum class Comparison { Equal, Better, Worse };
9052}
9053
9054/// Compares the enable_if attributes of two FunctionDecls, for the purposes of
9055/// overload resolution.
9056///
9057/// Cand1's set of enable_if attributes are said to be "better" than Cand2's iff
9058/// Cand1's first N enable_if attributes have precisely the same conditions as
9059/// Cand2's first N enable_if attributes (where N = the number of enable_if
9060/// attributes on Cand2), and Cand1 has more than N enable_if attributes.
9061///
9062/// Note that you can have a pair of candidates such that Cand1's enable_if
9063/// attributes are worse than Cand2's, and Cand2's enable_if attributes are
9064/// worse than Cand1's.
9065static Comparison compareEnableIfAttrs(const Sema &S, const FunctionDecl *Cand1,
9066 const FunctionDecl *Cand2) {
9067 // Common case: One (or both) decls don't have enable_if attrs.
9068 bool Cand1Attr = Cand1->hasAttr<EnableIfAttr>();
9069 bool Cand2Attr = Cand2->hasAttr<EnableIfAttr>();
9070 if (!Cand1Attr || !Cand2Attr) {
9071 if (Cand1Attr == Cand2Attr)
9072 return Comparison::Equal;
9073 return Cand1Attr ? Comparison::Better : Comparison::Worse;
9074 }
9075
9076 auto Cand1Attrs = Cand1->specific_attrs<EnableIfAttr>();
9077 auto Cand2Attrs = Cand2->specific_attrs<EnableIfAttr>();
9078
9079 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
9080 for (auto Pair : zip_longest(Cand1Attrs, Cand2Attrs)) {
9081 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
9082 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
9083
9084 // It's impossible for Cand1 to be better than (or equal to) Cand2 if Cand1
9085 // has fewer enable_if attributes than Cand2, and vice versa.
9086 if (!Cand1A)
9087 return Comparison::Worse;
9088 if (!Cand2A)
9089 return Comparison::Better;
9090
9091 Cand1ID.clear();
9092 Cand2ID.clear();
9093
9094 (*Cand1A)->getCond()->Profile(Cand1ID, S.getASTContext(), true);
9095 (*Cand2A)->getCond()->Profile(Cand2ID, S.getASTContext(), true);
9096 if (Cand1ID != Cand2ID)
9097 return Comparison::Worse;
9098 }
9099
9100 return Comparison::Equal;
9101}
9102
9103static bool isBetterMultiversionCandidate(const OverloadCandidate &Cand1,
9104 const OverloadCandidate &Cand2) {
9105 if (!Cand1.Function || !Cand1.Function->isMultiVersion() || !Cand2.Function ||
9106 !Cand2.Function->isMultiVersion())
9107 return false;
9108
9109 // If Cand1 is invalid, it cannot be a better match, if Cand2 is invalid, this
9110 // is obviously better.
9111 if (Cand1.Function->isInvalidDecl()) return false;
9112 if (Cand2.Function->isInvalidDecl()) return true;
9113
9114 // If this is a cpu_dispatch/cpu_specific multiversion situation, prefer
9115 // cpu_dispatch, else arbitrarily based on the identifiers.
9116 bool Cand1CPUDisp = Cand1.Function->hasAttr<CPUDispatchAttr>();
9117 bool Cand2CPUDisp = Cand2.Function->hasAttr<CPUDispatchAttr>();
9118 const auto *Cand1CPUSpec = Cand1.Function->getAttr<CPUSpecificAttr>();
9119 const auto *Cand2CPUSpec = Cand2.Function->getAttr<CPUSpecificAttr>();
9120
9121 if (!Cand1CPUDisp && !Cand2CPUDisp && !Cand1CPUSpec && !Cand2CPUSpec)
9122 return false;
9123
9124 if (Cand1CPUDisp && !Cand2CPUDisp)
9125 return true;
9126 if (Cand2CPUDisp && !Cand1CPUDisp)
9127 return false;
9128
9129 if (Cand1CPUSpec && Cand2CPUSpec) {
9130 if (Cand1CPUSpec->cpus_size() != Cand2CPUSpec->cpus_size())
9131 return Cand1CPUSpec->cpus_size() < Cand2CPUSpec->cpus_size();
9132
9133 std::pair<CPUSpecificAttr::cpus_iterator, CPUSpecificAttr::cpus_iterator>
9134 FirstDiff = std::mismatch(
9135 Cand1CPUSpec->cpus_begin(), Cand1CPUSpec->cpus_end(),
9136 Cand2CPUSpec->cpus_begin(),
9137 [](const IdentifierInfo *LHS, const IdentifierInfo *RHS) {
9138 return LHS->getName() == RHS->getName();
9139 });
9140
9141 assert(FirstDiff.first != Cand1CPUSpec->cpus_end() &&
9142 "Two different cpu-specific versions should not have the same "
9143 "identifier list, otherwise they'd be the same decl!");
9144 return (*FirstDiff.first)->getName() < (*FirstDiff.second)->getName();
9145 }
9146 llvm_unreachable("No way to get here unless both had cpu_dispatch");
9147}
9148
9149/// isBetterOverloadCandidate - Determines whether the first overload
9150/// candidate is a better candidate than the second (C++ 13.3.3p1).
9151bool clang::isBetterOverloadCandidate(
9152 Sema &S, const OverloadCandidate &Cand1, const OverloadCandidate &Cand2,
9153 SourceLocation Loc, OverloadCandidateSet::CandidateSetKind Kind) {
9154 // Define viable functions to be better candidates than non-viable
9155 // functions.
9156 if (!Cand2.Viable)
9157 return Cand1.Viable;
9158 else if (!Cand1.Viable)
9159 return false;
9160
9161 // C++ [over.match.best]p1:
9162 //
9163 // -- if F is a static member function, ICS1(F) is defined such
9164 // that ICS1(F) is neither better nor worse than ICS1(G) for
9165 // any function G, and, symmetrically, ICS1(G) is neither
9166 // better nor worse than ICS1(F).
9167 unsigned StartArg = 0;
9168 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
9169 StartArg = 1;
9170
9171 auto IsIllFormedConversion = [&](const ImplicitConversionSequence &ICS) {
9172 // We don't allow incompatible pointer conversions in C++.
9173 if (!S.getLangOpts().CPlusPlus)
9174 return ICS.isStandard() &&
9175 ICS.Standard.Second == ICK_Incompatible_Pointer_Conversion;
9176
9177 // The only ill-formed conversion we allow in C++ is the string literal to
9178 // char* conversion, which is only considered ill-formed after C++11.
9179 return S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
9180 hasDeprecatedStringLiteralToCharPtrConversion(ICS);
9181 };
9182
9183 // Define functions that don't require ill-formed conversions for a given
9184 // argument to be better candidates than functions that do.
9185 unsigned NumArgs = Cand1.Conversions.size();
9186 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
9187 bool HasBetterConversion = false;
9188 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9189 bool Cand1Bad = IsIllFormedConversion(Cand1.Conversions[ArgIdx]);
9190 bool Cand2Bad = IsIllFormedConversion(Cand2.Conversions[ArgIdx]);
9191 if (Cand1Bad != Cand2Bad) {
9192 if (Cand1Bad)
9193 return false;
9194 HasBetterConversion = true;
9195 }
9196 }
9197
9198 if (HasBetterConversion)
9199 return true;
9200
9201 // C++ [over.match.best]p1:
9202 // A viable function F1 is defined to be a better function than another
9203 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
9204 // conversion sequence than ICSi(F2), and then...
9205 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
9206 switch (CompareImplicitConversionSequences(S, Loc,
9207 Cand1.Conversions[ArgIdx],
9208 Cand2.Conversions[ArgIdx])) {
9209 case ImplicitConversionSequence::Better:
9210 // Cand1 has a better conversion sequence.
9211 HasBetterConversion = true;
9212 break;
9213
9214 case ImplicitConversionSequence::Worse:
9215 // Cand1 can't be better than Cand2.
9216 return false;
9217
9218 case ImplicitConversionSequence::Indistinguishable:
9219 // Do nothing.
9220 break;
9221 }
9222 }
9223
9224 // -- for some argument j, ICSj(F1) is a better conversion sequence than
9225 // ICSj(F2), or, if not that,
9226 if (HasBetterConversion)
9227 return true;
9228
9229 // -- the context is an initialization by user-defined conversion
9230 // (see 8.5, 13.3.1.5) and the standard conversion sequence
9231 // from the return type of F1 to the destination type (i.e.,
9232 // the type of the entity being initialized) is a better
9233 // conversion sequence than the standard conversion sequence
9234 // from the return type of F2 to the destination type.
9235 if (Kind == OverloadCandidateSet::CSK_InitByUserDefinedConversion &&
9236 Cand1.Function && Cand2.Function &&
9237 isa<CXXConversionDecl>(Cand1.Function) &&
9238 isa<CXXConversionDecl>(Cand2.Function)) {
9239 // First check whether we prefer one of the conversion functions over the
9240 // other. This only distinguishes the results in non-standard, extension
9241 // cases such as the conversion from a lambda closure type to a function
9242 // pointer or block.
9243 ImplicitConversionSequence::CompareKind Result =
9244 compareConversionFunctions(S, Cand1.Function, Cand2.Function);
9245 if (Result == ImplicitConversionSequence::Indistinguishable)
9246 Result = CompareStandardConversionSequences(S, Loc,
9247 Cand1.FinalConversion,
9248 Cand2.FinalConversion);
9249
9250 if (Result != ImplicitConversionSequence::Indistinguishable)
9251 return Result == ImplicitConversionSequence::Better;
9252
9253 // FIXME: Compare kind of reference binding if conversion functions
9254 // convert to a reference type used in direct reference binding, per
9255 // C++14 [over.match.best]p1 section 2 bullet 3.
9256 }
9257
9258 // FIXME: Work around a defect in the C++17 guaranteed copy elision wording,
9259 // as combined with the resolution to CWG issue 243.
9260 //
9261 // When the context is initialization by constructor ([over.match.ctor] or
9262 // either phase of [over.match.list]), a constructor is preferred over
9263 // a conversion function.
9264 if (Kind == OverloadCandidateSet::CSK_InitByConstructor && NumArgs == 1 &&
9265 Cand1.Function && Cand2.Function &&
9266 isa<CXXConstructorDecl>(Cand1.Function) !=
9267 isa<CXXConstructorDecl>(Cand2.Function))
9268 return isa<CXXConstructorDecl>(Cand1.Function);
9269
9270 // -- F1 is a non-template function and F2 is a function template
9271 // specialization, or, if not that,
9272 bool Cand1IsSpecialization = Cand1.Function &&
9273 Cand1.Function->getPrimaryTemplate();
9274 bool Cand2IsSpecialization = Cand2.Function &&
9275 Cand2.Function->getPrimaryTemplate();
9276 if (Cand1IsSpecialization != Cand2IsSpecialization)
9277 return Cand2IsSpecialization;
9278
9279 // -- F1 and F2 are function template specializations, and the function
9280 // template for F1 is more specialized than the template for F2
9281 // according to the partial ordering rules described in 14.5.5.2, or,
9282 // if not that,
9283 if (Cand1IsSpecialization && Cand2IsSpecialization) {
9284 if (FunctionTemplateDecl *BetterTemplate
9285 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
9286 Cand2.Function->getPrimaryTemplate(),
9287 Loc,
9288 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
9289 : TPOC_Call,
9290 Cand1.ExplicitCallArguments,
9291 Cand2.ExplicitCallArguments))
9292 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
9293 }
9294
9295 // FIXME: Work around a defect in the C++17 inheriting constructor wording.
9296 // A derived-class constructor beats an (inherited) base class constructor.
9297 bool Cand1IsInherited =
9298 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand1.FoundDecl.getDecl());
9299 bool Cand2IsInherited =
9300 dyn_cast_or_null<ConstructorUsingShadowDecl>(Cand2.FoundDecl.getDecl());
9301 if (Cand1IsInherited != Cand2IsInherited)
9302 return Cand2IsInherited;
9303 else if (Cand1IsInherited) {
9304 assert(Cand2IsInherited);
9305 auto *Cand1Class = cast<CXXRecordDecl>(Cand1.Function->getDeclContext());
9306 auto *Cand2Class = cast<CXXRecordDecl>(Cand2.Function->getDeclContext());
9307 if (Cand1Class->isDerivedFrom(Cand2Class))
9308 return true;
9309 if (Cand2Class->isDerivedFrom(Cand1Class))
9310 return false;
9311 // Inherited from sibling base classes: still ambiguous.
9312 }
9313
9314 // Check C++17 tie-breakers for deduction guides.
9315 {
9316 auto *Guide1 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand1.Function);
9317 auto *Guide2 = dyn_cast_or_null<CXXDeductionGuideDecl>(Cand2.Function);
9318 if (Guide1 && Guide2) {
9319 // -- F1 is generated from a deduction-guide and F2 is not
9320 if (Guide1->isImplicit() != Guide2->isImplicit())
9321 return Guide2->isImplicit();
9322
9323 // -- F1 is the copy deduction candidate(16.3.1.8) and F2 is not
9324 if (Guide1->isCopyDeductionCandidate())
9325 return true;
9326 }
9327 }
9328
9329 // Check for enable_if value-based overload resolution.
9330 if (Cand1.Function && Cand2.Function) {
9331 Comparison Cmp = compareEnableIfAttrs(S, Cand1.Function, Cand2.Function);
9332 if (Cmp != Comparison::Equal)
9333 return Cmp == Comparison::Better;
9334 }
9335
9336 if (S.getLangOpts().CUDA && Cand1.Function && Cand2.Function) {
9337 FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9338 return S.IdentifyCUDAPreference(Caller, Cand1.Function) >
9339 S.IdentifyCUDAPreference(Caller, Cand2.Function);
9340 }
9341
9342 bool HasPS1 = Cand1.Function != nullptr &&
9343 functionHasPassObjectSizeParams(Cand1.Function);
9344 bool HasPS2 = Cand2.Function != nullptr &&
9345 functionHasPassObjectSizeParams(Cand2.Function);
9346 if (HasPS1 != HasPS2 && HasPS1)
9347 return true;
9348
9349 return isBetterMultiversionCandidate(Cand1, Cand2);
9350}
9351
9352/// Determine whether two declarations are "equivalent" for the purposes of
9353/// name lookup and overload resolution. This applies when the same internal/no
9354/// linkage entity is defined by two modules (probably by textually including
9355/// the same header). In such a case, we don't consider the declarations to
9356/// declare the same entity, but we also don't want lookups with both
9357/// declarations visible to be ambiguous in some cases (this happens when using
9358/// a modularized libstdc++).
9359bool Sema::isEquivalentInternalLinkageDeclaration(const NamedDecl *A,
9360 const NamedDecl *B) {
9361 auto *VA = dyn_cast_or_null<ValueDecl>(A);
9362 auto *VB = dyn_cast_or_null<ValueDecl>(B);
9363 if (!VA || !VB)
9364 return false;
9365
9366 // The declarations must be declaring the same name as an internal linkage
9367 // entity in different modules.
9368 if (!VA->getDeclContext()->getRedeclContext()->Equals(
9369 VB->getDeclContext()->getRedeclContext()) ||
9370 getOwningModule(const_cast<ValueDecl *>(VA)) ==
9371 getOwningModule(const_cast<ValueDecl *>(VB)) ||
9372 VA->isExternallyVisible() || VB->isExternallyVisible())
9373 return false;
9374
9375 // Check that the declarations appear to be equivalent.
9376 //
9377 // FIXME: Checking the type isn't really enough to resolve the ambiguity.
9378 // For constants and functions, we should check the initializer or body is
9379 // the same. For non-constant variables, we shouldn't allow it at all.
9380 if (Context.hasSameType(VA->getType(), VB->getType()))
9381 return true;
9382
9383 // Enum constants within unnamed enumerations will have different types, but
9384 // may still be similar enough to be interchangeable for our purposes.
9385 if (auto *EA = dyn_cast<EnumConstantDecl>(VA)) {
9386 if (auto *EB = dyn_cast<EnumConstantDecl>(VB)) {
9387 // Only handle anonymous enums. If the enumerations were named and
9388 // equivalent, they would have been merged to the same type.
9389 auto *EnumA = cast<EnumDecl>(EA->getDeclContext());
9390 auto *EnumB = cast<EnumDecl>(EB->getDeclContext());
9391 if (EnumA->hasNameForLinkage() || EnumB->hasNameForLinkage() ||
9392 !Context.hasSameType(EnumA->getIntegerType(),
9393 EnumB->getIntegerType()))
9394 return false;
9395 // Allow this only if the value is the same for both enumerators.
9396 return llvm::APSInt::isSameValue(EA->getInitVal(), EB->getInitVal());
9397 }
9398 }
9399
9400 // Nothing else is sufficiently similar.
9401 return false;
9402}
9403
9404void Sema::diagnoseEquivalentInternalLinkageDeclarations(
9405 SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv) {
9406 Diag(Loc, diag::ext_equivalent_internal_linkage_decl_in_modules) << D;
9407
9408 Module *M = getOwningModule(const_cast<NamedDecl*>(D));
9409 Diag(D->getLocation(), diag::note_equivalent_internal_linkage_decl)
9410 << !M << (M ? M->getFullModuleName() : "");
9411
9412 for (auto *E : Equiv) {
9413 Module *M = getOwningModule(const_cast<NamedDecl*>(E));
9414 Diag(E->getLocation(), diag::note_equivalent_internal_linkage_decl)
9415 << !M << (M ? M->getFullModuleName() : "");
9416 }
9417}
9418
9419/// Computes the best viable function (C++ 13.3.3)
9420/// within an overload candidate set.
9421///
9422/// \param Loc The location of the function name (or operator symbol) for
9423/// which overload resolution occurs.
9424///
9425/// \param Best If overload resolution was successful or found a deleted
9426/// function, \p Best points to the candidate function found.
9427///
9428/// \returns The result of overload resolution.
9429OverloadingResult
9430OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
9431 iterator &Best) {
9432 llvm::SmallVector<OverloadCandidate *, 16> Candidates;
9433 std::transform(begin(), end(), std::back_inserter(Candidates),
9434 [](OverloadCandidate &Cand) { return &Cand; });
9435
9436 // [CUDA] HD->H or HD->D calls are technically not allowed by CUDA but
9437 // are accepted by both clang and NVCC. However, during a particular
9438 // compilation mode only one call variant is viable. We need to
9439 // exclude non-viable overload candidates from consideration based
9440 // only on their host/device attributes. Specifically, if one
9441 // candidate call is WrongSide and the other is SameSide, we ignore
9442 // the WrongSide candidate.
9443 if (S.getLangOpts().CUDA) {
9444 const FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext);
9445 bool ContainsSameSideCandidate =
9446 llvm::any_of(Candidates, [&](OverloadCandidate *Cand) {
9447 return Cand->Function &&
9448 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9449 Sema::CFP_SameSide;
9450 });
9451 if (ContainsSameSideCandidate) {
9452 auto IsWrongSideCandidate = [&](OverloadCandidate *Cand) {
9453 return Cand->Function &&
9454 S.IdentifyCUDAPreference(Caller, Cand->Function) ==
9455 Sema::CFP_WrongSide;
9456 };
9457 llvm::erase_if(Candidates, IsWrongSideCandidate);
9458 }
9459 }
9460
9461 // Find the best viable function.
9462 Best = end();
9463 for (auto *Cand : Candidates)
9464 if (Cand->Viable)
9465 if (Best == end() ||
9466 isBetterOverloadCandidate(S, *Cand, *Best, Loc, Kind))
9467 Best = Cand;
9468
9469 // If we didn't find any viable functions, abort.
9470 if (Best == end())
9471 return OR_No_Viable_Function;
9472
9473 llvm::SmallVector<const NamedDecl *, 4> EquivalentCands;
9474
9475 // Make sure that this function is better than every other viable
9476 // function. If not, we have an ambiguity.
9477 for (auto *Cand : Candidates) {
9478 if (Cand->Viable && Cand != Best &&
9479 !isBetterOverloadCandidate(S, *Best, *Cand, Loc, Kind)) {
9480 if (S.isEquivalentInternalLinkageDeclaration(Best->Function,
9481 Cand->Function)) {
9482 EquivalentCands.push_back(Cand->Function);
9483 continue;
9484 }
9485
9486 Best = end();
9487 return OR_Ambiguous;
9488 }
9489 }
9490
9491 // Best is the best viable function.
9492 if (Best->Function && Best->Function->isDeleted())
9493 return OR_Deleted;
9494
9495 if (!EquivalentCands.empty())
9496 S.diagnoseEquivalentInternalLinkageDeclarations(Loc, Best->Function,
9497 EquivalentCands);
9498
9499 return OR_Success;
9500}
9501
9502namespace {
9503
9504enum OverloadCandidateKind {
9505 oc_function,
9506 oc_method,
9507 oc_constructor,
9508 oc_implicit_default_constructor,
9509 oc_implicit_copy_constructor,
9510 oc_implicit_move_constructor,
9511 oc_implicit_copy_assignment,
9512 oc_implicit_move_assignment,
9513 oc_inherited_constructor
9514};
9515
9516enum OverloadCandidateSelect {
9517 ocs_non_template,
9518 ocs_template,
9519 ocs_described_template,
9520};
9521
9522static std::pair<OverloadCandidateKind, OverloadCandidateSelect>
9523ClassifyOverloadCandidate(Sema &S, NamedDecl *Found, FunctionDecl *Fn,
9524 std::string &Description) {
9525
9526 bool isTemplate = Fn->isTemplateDecl() || Found->isTemplateDecl();
9527 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
9528 isTemplate = true;
9529 Description = S.getTemplateArgumentBindingsText(
9530 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
9531 }
9532
9533 OverloadCandidateSelect Select = [&]() {
9534 if (!Description.empty())
9535 return ocs_described_template;
9536 return isTemplate ? ocs_template : ocs_non_template;
9537 }();
9538
9539 OverloadCandidateKind Kind = [&]() {
9540 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
9541 if (!Ctor->isImplicit()) {
9542 if (isa<ConstructorUsingShadowDecl>(Found))
9543 return oc_inherited_constructor;
9544 else
9545 return oc_constructor;
9546 }
9547
9548 if (Ctor->isDefaultConstructor())
9549 return oc_implicit_default_constructor;
9550
9551 if (Ctor->isMoveConstructor())
9552 return oc_implicit_move_constructor;
9553
9554 assert(Ctor->isCopyConstructor() &&
9555 "unexpected sort of implicit constructor");
9556 return oc_implicit_copy_constructor;
9557 }
9558
9559 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
9560 // This actually gets spelled 'candidate function' for now, but
9561 // it doesn't hurt to split it out.
9562 if (!Meth->isImplicit())
9563 return oc_method;
9564
9565 if (Meth->isMoveAssignmentOperator())
9566 return oc_implicit_move_assignment;
9567
9568 if (Meth->isCopyAssignmentOperator())
9569 return oc_implicit_copy_assignment;
9570
9571 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
9572 return oc_method;
9573 }
9574
9575 return oc_function;
9576 }();
9577
9578 return std::make_pair(Kind, Select);
9579}
9580
9581void MaybeEmitInheritedConstructorNote(Sema &S, Decl *FoundDecl) {
9582 // FIXME: It'd be nice to only emit a note once per using-decl per overload
9583 // set.
9584 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl))
9585 S.Diag(FoundDecl->getLocation(),
9586 diag::note_ovl_candidate_inherited_constructor)
9587 << Shadow->getNominatedBaseClass();
9588}
9589
9590} // end anonymous namespace
9591
9592static bool isFunctionAlwaysEnabled(const ASTContext &Ctx,
9593 const FunctionDecl *FD) {
9594 for (auto *EnableIf : FD->specific_attrs<EnableIfAttr>()) {
9595 bool AlwaysTrue;
9596 if (EnableIf->getCond()->isValueDependent() ||
9597 !EnableIf->getCond()->EvaluateAsBooleanCondition(AlwaysTrue, Ctx))
9598 return false;
9599 if (!AlwaysTrue)
9600 return false;
9601 }
9602 return true;
9603}
9604
9605/// Returns true if we can take the address of the function.
9606///
9607/// \param Complain - If true, we'll emit a diagnostic
9608/// \param InOverloadResolution - For the purposes of emitting a diagnostic, are
9609/// we in overload resolution?
9610/// \param Loc - The location of the statement we're complaining about. Ignored
9611/// if we're not complaining, or if we're in overload resolution.
9612static bool checkAddressOfFunctionIsAvailable(Sema &S, const FunctionDecl *FD,
9613 bool Complain,
9614 bool InOverloadResolution,
9615 SourceLocation Loc) {
9616 if (!isFunctionAlwaysEnabled(S.Context, FD)) {
9617 if (Complain) {
9618 if (InOverloadResolution)
9619 S.Diag(FD->getBeginLoc(),
9620 diag::note_addrof_ovl_candidate_disabled_by_enable_if_attr);
9621 else
9622 S.Diag(Loc, diag::err_addrof_function_disabled_by_enable_if_attr) << FD;
9623 }
9624 return false;
9625 }
9626
9627 auto I = llvm::find_if(FD->parameters(), [](const ParmVarDecl *P) {
9628 return P->hasAttr<PassObjectSizeAttr>();
9629 });
9630 if (I == FD->param_end())
9631 return true;
9632
9633 if (Complain) {
9634 // Add one to ParamNo because it's user-facing
9635 unsigned ParamNo = std::distance(FD->param_begin(), I) + 1;
9636 if (InOverloadResolution)
9637 S.Diag(FD->getLocation(),
9638 diag::note_ovl_candidate_has_pass_object_size_params)
9639 << ParamNo;
9640 else
9641 S.Diag(Loc, diag::err_address_of_function_with_pass_object_size_params)
9642 << FD << ParamNo;
9643 }
9644 return false;
9645}
9646
9647static bool checkAddressOfCandidateIsAvailable(Sema &S,
9648 const FunctionDecl *FD) {
9649 return checkAddressOfFunctionIsAvailable(S, FD, /*Complain=*/true,
9650 /*InOverloadResolution=*/true,
9651 /*Loc=*/SourceLocation());
9652}
9653
9654bool Sema::checkAddressOfFunctionIsAvailable(const FunctionDecl *Function,
9655 bool Complain,
9656 SourceLocation Loc) {
9657 return ::checkAddressOfFunctionIsAvailable(*this, Function, Complain,
9658 /*InOverloadResolution=*/false,
9659 Loc);
9660}
9661
9662// Notes the location of an overload candidate.
9663void Sema::NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn,
9664 QualType DestType, bool TakingAddress) {
9665 if (TakingAddress && !checkAddressOfCandidateIsAvailable(*this, Fn))
9666 return;
9667 if (Fn->isMultiVersion() && Fn->hasAttr<TargetAttr>() &&
9668 !Fn->getAttr<TargetAttr>()->isDefaultVersion())
9669 return;
9670
9671 std::string FnDesc;
9672 std::pair<OverloadCandidateKind, OverloadCandidateSelect> KSPair =
9673 ClassifyOverloadCandidate(*this, Found, Fn, FnDesc);
9674 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
9675 << (unsigned)KSPair.first << (unsigned)KSPair.second
9676 << Fn << FnDesc;
9677
9678 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
9679 Diag(Fn->getLocation(), PD);
9680 MaybeEmitInheritedConstructorNote(*this, Found);
9681}
9682
9683// Notes the location of all overload candidates designated through
9684// OverloadedExpr
9685void Sema::NoteAllOverloadCandidates(Expr *OverloadedExpr, QualType DestType,
9686 bool TakingAddress) {
9687 assert(OverloadedExpr->getType() == Context.OverloadTy);
9688
9689 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
9690 OverloadExpr *OvlExpr = Ovl.Expression;
9691
9692 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9693 IEnd = OvlExpr->decls_end();
9694 I != IEnd; ++I) {
9695 if (FunctionTemplateDecl *FunTmpl =
9696 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
9697 NoteOverloadCandidate(*I, FunTmpl->getTemplatedDecl(), DestType,
9698 TakingAddress);
9699 } else if (FunctionDecl *Fun
9700 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
9701 NoteOverloadCandidate(*I, Fun, DestType, TakingAddress);
9702 }
9703 }
9704}
9705
9706/// Diagnoses an ambiguous conversion. The partial diagnostic is the
9707/// "lead" diagnostic; it will be given two arguments, the source and
9708/// target types of the conversion.
9709void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
9710 Sema &S,
9711 SourceLocation CaretLoc,
9712 const PartialDiagnostic &PDiag) const {
9713 S.Diag(CaretLoc, PDiag)
9714 << Ambiguous.getFromType() << Ambiguous.getToType();
9715 // FIXME: The note limiting machinery is borrowed from
9716 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
9717 // refactoring here.
9718 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9719 unsigned CandsShown = 0;
9720 AmbiguousConversionSequence::const_iterator I, E;
9721 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
9722 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9723 break;
9724 ++CandsShown;
9725 S.NoteOverloadCandidate(I->first, I->second);
9726 }
9727 if (I != E)
9728 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
9729}
9730
9731static void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand,
9732 unsigned I, bool TakingCandidateAddress) {
9733 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
9734 assert(Conv.isBad());
9735 assert(Cand->Function && "for now, candidate must be a function");
9736 FunctionDecl *Fn = Cand->Function;
9737
9738 // There's a conversion slot for the object argument if this is a
9739 // non-constructor method. Note that 'I' corresponds the
9740 // conversion-slot index.
9741 bool isObjectArgument = false;
9742 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
9743 if (I == 0)
9744 isObjectArgument = true;
9745 else
9746 I--;
9747 }
9748
9749 std::string FnDesc;
9750 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
9751 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
9752
9753 Expr *FromExpr = Conv.Bad.FromExpr;
9754 QualType FromTy = Conv.Bad.getFromType();
9755 QualType ToTy = Conv.Bad.getToType();
9756
9757 if (FromTy == S.Context.OverloadTy) {
9758 assert(FromExpr && "overload set argument came from implicit argument?");
9759 Expr *E = FromExpr->IgnoreParens();
9760 if (isa<UnaryOperator>(E))
9761 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
9762 DeclarationName Name = cast<OverloadExpr>(E)->getName();
9763
9764 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
9765 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9766 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
9767 << Name << I + 1;
9768 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9769 return;
9770 }
9771
9772 // Do some hand-waving analysis to see if the non-viability is due
9773 // to a qualifier mismatch.
9774 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
9775 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
9776 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
9777 CToTy = RT->getPointeeType();
9778 else {
9779 // TODO: detect and diagnose the full richness of const mismatches.
9780 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
9781 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>()) {
9782 CFromTy = FromPT->getPointeeType();
9783 CToTy = ToPT->getPointeeType();
9784 }
9785 }
9786
9787 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
9788 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
9789 Qualifiers FromQs = CFromTy.getQualifiers();
9790 Qualifiers ToQs = CToTy.getQualifiers();
9791
9792 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
9793 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
9794 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9795 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9796 << ToTy << (unsigned)isObjectArgument << I + 1;
9797 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9798 return;
9799 }
9800
9801 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
9803 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9804 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9805 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
9806 << (unsigned)isObjectArgument << I + 1;
9807 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9808 return;
9809 }
9810
9811 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
9812 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
9813 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9814 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9815 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
9816 << (unsigned)isObjectArgument << I + 1;
9817 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9818 return;
9819 }
9820
9821 if (FromQs.hasUnaligned() != ToQs.hasUnaligned()) {
9822 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_unaligned)
9823 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9824 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9825 << FromQs.hasUnaligned() << I + 1;
9826 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9827 return;
9828 }
9829
9830 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
9831 assert(CVR && "unexpected qualifiers mismatch");
9832
9833 if (isObjectArgument) {
9834 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
9835 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9836 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9837 << (CVR - 1);
9838 } else {
9839 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
9840 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9841 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9842 << (CVR - 1) << I + 1;
9843 }
9844 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9845 return;
9846 }
9847
9848 // Special diagnostic for failure to convert an initializer list, since
9849 // telling the user that it has type void is not useful.
9850 if (FromExpr && isa<InitListExpr>(FromExpr)) {
9851 // XXXAR: it would be nice if we could somehow diagnose capability -> pointer
9852 // narrowing conversions here instead of just printing candidate not viable
9853 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
9854 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9855 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9856 << ToTy << (unsigned)isObjectArgument << I + 1;
9857 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9858 return;
9859 }
9860
9861 // Diagnose references or pointers to incomplete types differently,
9862 // since it's far from impossible that the incompleteness triggered
9863 // the failure.
9864 QualType TempFromTy = FromTy.getNonReferenceType();
9865 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
9866 TempFromTy = PTy->getPointeeType();
9867 if (TempFromTy->isIncompleteType()) {
9868 // Emit the generic diagnostic and, optionally, add the hints to it.
9869 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
9870 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9871 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9872 << ToTy << (unsigned)isObjectArgument << I + 1
9873 << (unsigned)(Cand->Fix.Kind);
9874
9875 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9876 return;
9877 }
9878
9879 // Diagnose base -> derived pointer conversions.
9880 unsigned BaseToDerivedConversion = 0;
9881 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
9882 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
9883 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9884 FromPtrTy->getPointeeType()) &&
9885 !FromPtrTy->getPointeeType()->isIncompleteType() &&
9886 !ToPtrTy->getPointeeType()->isIncompleteType() &&
9887 S.IsDerivedFrom(SourceLocation(), ToPtrTy->getPointeeType(),
9888 FromPtrTy->getPointeeType()))
9889 BaseToDerivedConversion = 1;
9890 }
9891 } else if (const ObjCObjectPointerType *FromPtrTy
9892 = FromTy->getAs<ObjCObjectPointerType>()) {
9893 if (const ObjCObjectPointerType *ToPtrTy
9894 = ToTy->getAs<ObjCObjectPointerType>())
9895 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
9896 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
9897 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
9898 FromPtrTy->getPointeeType()) &&
9899 FromIface->isSuperClassOf(ToIface))
9900 BaseToDerivedConversion = 2;
9901 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
9902 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
9903 !FromTy->isIncompleteType() &&
9904 !ToRefTy->getPointeeType()->isIncompleteType() &&
9905 S.IsDerivedFrom(SourceLocation(), ToRefTy->getPointeeType(), FromTy)) {
9906 BaseToDerivedConversion = 3;
9907 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
9908 ToTy.getNonReferenceType().getCanonicalType() ==
9909 FromTy.getNonReferenceType().getCanonicalType()) {
9910 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
9911 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9912 << (unsigned)isObjectArgument << I + 1
9913 << (FromExpr ? FromExpr->getSourceRange() : SourceRange());
9914 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9915 return;
9916 }
9917 }
9918
9919 if (BaseToDerivedConversion) {
9920 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_base_to_derived_conv)
9921 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9922 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9923 << (BaseToDerivedConversion - 1) << FromTy << ToTy << I + 1;
9924 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9925 return;
9926 }
9927
9928 if (isa<ObjCObjectPointerType>(CFromTy) &&
9929 isa<PointerType>(CToTy)) {
9930 Qualifiers FromQs = CFromTy.getQualifiers();
9931 Qualifiers ToQs = CToTy.getQualifiers();
9932 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
9933 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
9934 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
9935 << FnDesc << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
9936 << FromTy << ToTy << (unsigned)isObjectArgument << I + 1;
9937 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9938 return;
9939 }
9940 }
9941
9942 if (TakingCandidateAddress &&
9943 !checkAddressOfCandidateIsAvailable(S, Cand->Function))
9944 return;
9945
9946 // Emit the generic diagnostic and, optionally, add the hints to it.
9947 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
9948 FDiag << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
9949 << (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << FromTy
9950 << ToTy << (unsigned)isObjectArgument << I + 1
9951 << (unsigned)(Cand->Fix.Kind);
9952
9953 // If we can fix the conversion, suggest the FixIts.
9954 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
9955 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
9956 FDiag << *HI;
9957 S.Diag(Fn->getLocation(), FDiag);
9958
9959 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
9960}
9961
9962/// Additional arity mismatch diagnosis specific to a function overload
9963/// candidates. This is not covered by the more general DiagnoseArityMismatch()
9964/// over a candidate in any candidate set.
9965static bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
9966 unsigned NumArgs) {
9967 FunctionDecl *Fn = Cand->Function;
9968 unsigned MinParams = Fn->getMinRequiredArguments();
9969
9970 // With invalid overloaded operators, it's possible that we think we
9971 // have an arity mismatch when in fact it looks like we have the
9972 // right number of arguments, because only overloaded operators have
9973 // the weird behavior of overloading member and non-member functions.
9974 // Just don't report anything.
9975 if (Fn->isInvalidDecl() &&
9976 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
9977 return true;
9978
9979 if (NumArgs < MinParams) {
9980 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
9981 (Cand->FailureKind == ovl_fail_bad_deduction &&
9982 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
9983 } else {
9984 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
9985 (Cand->FailureKind == ovl_fail_bad_deduction &&
9986 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
9987 }
9988
9989 return false;
9990}
9991
9992/// General arity mismatch diagnosis over a candidate in a candidate set.
9993static void DiagnoseArityMismatch(Sema &S, NamedDecl *Found, Decl *D,
9994 unsigned NumFormalArgs) {
9995 assert(isa<FunctionDecl>(D) &&
9996 "The templated declaration should at least be a function"
9997 " when diagnosing bad template argument deduction due to too many"
9998 " or too few arguments");
9999
10000 FunctionDecl *Fn = cast<FunctionDecl>(D);
10001
10002 // TODO: treat calls to a missing default constructor as a special case
10003 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
10004 unsigned MinParams = Fn->getMinRequiredArguments();
10005
10006 // at least / at most / exactly
10007 unsigned mode, modeCount;
10008 if (NumFormalArgs < MinParams) {
10009 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
10010 FnTy->isTemplateVariadic())
10011 mode = 0; // "at least"
10012 else
10013 mode = 2; // "exactly"
10014 modeCount = MinParams;
10015 } else {
10016 if (MinParams != FnTy->getNumParams())
10017 mode = 1; // "at most"
10018 else
10019 mode = 2; // "exactly"
10020 modeCount = FnTy->getNumParams();
10021 }
10022
10023 std::string Description;
10024 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10025 ClassifyOverloadCandidate(S, Found, Fn, Description);
10026
10027 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
10028 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
10029 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10030 << Description << mode << Fn->getParamDecl(0) << NumFormalArgs;
10031 else
10032 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
10033 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second
10034 << Description << mode << modeCount << NumFormalArgs;
10035
10036 MaybeEmitInheritedConstructorNote(S, Found);
10037}
10038
10039/// Arity mismatch diagnosis specific to a function overload candidate.
10040static void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
10041 unsigned NumFormalArgs) {
10042 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
10043 DiagnoseArityMismatch(S, Cand->FoundDecl, Cand->Function, NumFormalArgs);
10044}
10045
10046static TemplateDecl *getDescribedTemplate(Decl *Templated) {
10047 if (TemplateDecl *TD = Templated->getDescribedTemplate())
10048 return TD;
10049 llvm_unreachable("Unsupported: Getting the described template declaration"
10050 " for bad deduction diagnosis");
10051}
10052
10053/// Diagnose a failed template-argument deduction.
10054static void DiagnoseBadDeduction(Sema &S, NamedDecl *Found, Decl *Templated,
10055 DeductionFailureInfo &DeductionFailure,
10056 unsigned NumArgs,
10057 bool TakingCandidateAddress) {
10058 TemplateParameter Param = DeductionFailure.getTemplateParameter();
10059 NamedDecl *ParamD;
10060 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
10061 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
10062 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
10063 switch (DeductionFailure.Result) {
10064 case Sema::TDK_Success:
10065 llvm_unreachable("TDK_success while diagnosing bad deduction");
10066
10067 case Sema::TDK_Incomplete: {
10068 assert(ParamD && "no parameter found for incomplete deduction result");
10069 S.Diag(Templated->getLocation(),
10070 diag::note_ovl_candidate_incomplete_deduction)
10071 << ParamD->getDeclName();
10072 MaybeEmitInheritedConstructorNote(S, Found);
10073 return;
10074 }
10075
10076 case Sema::TDK_IncompletePack: {
10077 assert(ParamD && "no parameter found for incomplete deduction result");
10078 S.Diag(Templated->getLocation(),
10079 diag::note_ovl_candidate_incomplete_deduction_pack)
10080 << ParamD->getDeclName()
10081 << (DeductionFailure.getFirstArg()->pack_size() + 1)
10082 << *DeductionFailure.getFirstArg();
10083 MaybeEmitInheritedConstructorNote(S, Found);
10084 return;
10085 }
10086
10087 case Sema::TDK_Underqualified: {
10088 assert(ParamD && "no parameter found for bad qualifiers deduction result");
10089 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
10090
10091 QualType Param = DeductionFailure.getFirstArg()->getAsType();
10092
10093 // Param will have been canonicalized, but it should just be a
10094 // qualified version of ParamD, so move the qualifiers to that.
10095 QualifierCollector Qs;
10096 Qs.strip(Param);
10097 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
10098 assert(S.Context.hasSameType(Param, NonCanonParam));
10099
10100 // Arg has also been canonicalized, but there's nothing we can do
10101 // about that. It also doesn't matter as much, because it won't
10102 // have any template parameters in it (because deduction isn't
10103 // done on dependent types).
10104 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
10105
10106 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
10107 << ParamD->getDeclName() << Arg << NonCanonParam;
10108 MaybeEmitInheritedConstructorNote(S, Found);
10109 return;
10110 }
10111
10112 case Sema::TDK_Inconsistent: {
10113 assert(ParamD && "no parameter found for inconsistent deduction result");
10114 int which = 0;
10115 if (isa<TemplateTypeParmDecl>(ParamD))
10116 which = 0;
10117 else if (isa<NonTypeTemplateParmDecl>(ParamD)) {
10118 // Deduction might have failed because we deduced arguments of two
10119 // different types for a non-type template parameter.
10120 // FIXME: Use a different TDK value for this.
10121 QualType T1 =
10122 DeductionFailure.getFirstArg()->getNonTypeTemplateArgumentType();
10123 QualType T2 =
10124 DeductionFailure.getSecondArg()->getNonTypeTemplateArgumentType();
10125 if (!T1.isNull() && !T2.isNull() && !S.Context.hasSameType(T1, T2)) {
10126 S.Diag(Templated->getLocation(),
10127 diag::note_ovl_candidate_inconsistent_deduction_types)
10128 << ParamD->getDeclName() << *DeductionFailure.getFirstArg() << T1
10129 << *DeductionFailure.getSecondArg() << T2;
10130 MaybeEmitInheritedConstructorNote(S, Found);
10131 return;
10132 }
10133
10134 which = 1;
10135 } else {
10136 which = 2;
10137 }
10138
10139 S.Diag(Templated->getLocation(),
10140 diag::note_ovl_candidate_inconsistent_deduction)
10141 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
10142 << *DeductionFailure.getSecondArg();
10143 MaybeEmitInheritedConstructorNote(S, Found);
10144 return;
10145 }
10146
10147 case Sema::TDK_InvalidExplicitArguments:
10148 assert(ParamD && "no parameter found for invalid explicit arguments");
10149 if (ParamD->getDeclName())
10150 S.Diag(Templated->getLocation(),
10151 diag::note_ovl_candidate_explicit_arg_mismatch_named)
10152 << ParamD->getDeclName();
10153 else {
10154 int index = 0;
10155 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
10156 index = TTP->getIndex();
10157 else if (NonTypeTemplateParmDecl *NTTP
10158 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
10159 index = NTTP->getIndex();
10160 else
10161 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
10162 S.Diag(Templated->getLocation(),
10163 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
10164 << (index + 1);
10165 }
10166 MaybeEmitInheritedConstructorNote(S, Found);
10167 return;
10168
10169 case Sema::TDK_TooManyArguments:
10170 case Sema::TDK_TooFewArguments:
10171 DiagnoseArityMismatch(S, Found, Templated, NumArgs);
10172 return;
10173
10174 case Sema::TDK_InstantiationDepth:
10175 S.Diag(Templated->getLocation(),
10176 diag::note_ovl_candidate_instantiation_depth);
10177 MaybeEmitInheritedConstructorNote(S, Found);
10178 return;
10179
10180 case Sema::TDK_SubstitutionFailure: {
10181 // Format the template argument list into the argument string.
10182 SmallString<128> TemplateArgString;
10183 if (TemplateArgumentList *Args =
10184 DeductionFailure.getTemplateArgumentList()) {
10185 TemplateArgString = " ";
10186 TemplateArgString += S.getTemplateArgumentBindingsText(
10187 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10188 }
10189
10190 // If this candidate was disabled by enable_if, say so.
10191 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
10192 if (PDiag && PDiag->second.getDiagID() ==
10193 diag::err_typename_nested_not_found_enable_if) {
10194 // FIXME: Use the source range of the condition, and the fully-qualified
10195 // name of the enable_if template. These are both present in PDiag.
10196 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
10197 << "'enable_if'" << TemplateArgString;
10198 return;
10199 }
10200
10201 // We found a specific requirement that disabled the enable_if.
10202 if (PDiag && PDiag->second.getDiagID() ==
10203 diag::err_typename_nested_not_found_requirement) {
10204 S.Diag(Templated->getLocation(),
10205 diag::note_ovl_candidate_disabled_by_requirement)
10206 << PDiag->second.getStringArg(0) << TemplateArgString;
10207 return;
10208 }
10209
10210 // Format the SFINAE diagnostic into the argument string.
10211 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
10212 // formatted message in another diagnostic.
10213 SmallString<128> SFINAEArgString;
10214 SourceRange R;
10215 if (PDiag) {
10216 SFINAEArgString = ": ";
10217 R = SourceRange(PDiag->first, PDiag->first);
10218 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
10219 }
10220
10221 S.Diag(Templated->getLocation(),
10222 diag::note_ovl_candidate_substitution_failure)
10223 << TemplateArgString << SFINAEArgString << R;
10224 MaybeEmitInheritedConstructorNote(S, Found);
10225 return;
10226 }
10227
10228 case Sema::TDK_DeducedMismatch:
10229 case Sema::TDK_DeducedMismatchNested: {
10230 // Format the template argument list into the argument string.
10231 SmallString<128> TemplateArgString;
10232 if (TemplateArgumentList *Args =
10233 DeductionFailure.getTemplateArgumentList()) {
10234 TemplateArgString = " ";
10235 TemplateArgString += S.getTemplateArgumentBindingsText(
10236 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
10237 }
10238
10239 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_deduced_mismatch)
10240 << (*DeductionFailure.getCallArgIndex() + 1)
10241 << *DeductionFailure.getFirstArg() << *DeductionFailure.getSecondArg()
10242 << TemplateArgString
10243 << (DeductionFailure.Result == Sema::TDK_DeducedMismatchNested);
10244 break;
10245 }
10246
10247 case Sema::TDK_NonDeducedMismatch: {
10248 // FIXME: Provide a source location to indicate what we couldn't match.
10249 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
10250 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
10251 if (FirstTA.getKind() == TemplateArgument::Template &&
10252 SecondTA.getKind() == TemplateArgument::Template) {
10253 TemplateName FirstTN = FirstTA.getAsTemplate();
10254 TemplateName SecondTN = SecondTA.getAsTemplate();
10255 if (FirstTN.getKind() == TemplateName::Template &&
10256 SecondTN.getKind() == TemplateName::Template) {
10257 if (FirstTN.getAsTemplateDecl()->getName() ==
10258 SecondTN.getAsTemplateDecl()->getName()) {
10259 // FIXME: This fixes a bad diagnostic where both templates are named
10260 // the same. This particular case is a bit difficult since:
10261 // 1) It is passed as a string to the diagnostic printer.
10262 // 2) The diagnostic printer only attempts to find a better
10263 // name for types, not decls.
10264 // Ideally, this should folded into the diagnostic printer.
10265 S.Diag(Templated->getLocation(),
10266 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
10267 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
10268 return;
10269 }
10270 }
10271 }
10272
10273 if (TakingCandidateAddress && isa<FunctionDecl>(Templated) &&
10274 !checkAddressOfCandidateIsAvailable(S, cast<FunctionDecl>(Templated)))
10275 return;
10276
10277 // FIXME: For generic lambda parameters, check if the function is a lambda
10278 // call operator, and if so, emit a prettier and more informative
10279 // diagnostic that mentions 'auto' and lambda in addition to
10280 // (or instead of?) the canonical template type parameters.
10281 S.Diag(Templated->getLocation(),
10282 diag::note_ovl_candidate_non_deduced_mismatch)
10283 << FirstTA << SecondTA;
10284 return;
10285 }
10286 // TODO: diagnose these individually, then kill off
10287 // note_ovl_candidate_bad_deduction, which is uselessly vague.
10288 case Sema::TDK_MiscellaneousDeductionFailure:
10289 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
10290 MaybeEmitInheritedConstructorNote(S, Found);
10291 return;
10292 case Sema::TDK_CUDATargetMismatch:
10293 S.Diag(Templated->getLocation(),
10294 diag::note_cuda_ovl_candidate_target_mismatch);
10295 return;
10296 }
10297}
10298
10299/// Diagnose a failed template-argument deduction, for function calls.
10300static void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
10301 unsigned NumArgs,
10302 bool TakingCandidateAddress) {
10303 unsigned TDK = Cand->DeductionFailure.Result;
10304 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
10305 if (CheckArityMismatch(S, Cand, NumArgs))
10306 return;
10307 }
10308 DiagnoseBadDeduction(S, Cand->FoundDecl, Cand->Function, // pattern
10309 Cand->DeductionFailure, NumArgs, TakingCandidateAddress);
10310}
10311
10312/// CUDA: diagnose an invalid call across targets.
10313static void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
10314 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
10315 FunctionDecl *Callee = Cand->Function;
10316
10317 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
10318 CalleeTarget = S.IdentifyCUDATarget(Callee);
10319
10320 std::string FnDesc;
10321 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10322 ClassifyOverloadCandidate(S, Cand->FoundDecl, Callee, FnDesc);
10323
10324 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
10325 << (unsigned)FnKindPair.first << (unsigned)ocs_non_template
10326 << FnDesc /* Ignored */
10327 << CalleeTarget << CallerTarget;
10328
10329 // This could be an implicit constructor for which we could not infer the
10330 // target due to a collsion. Diagnose that case.
10331 CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Callee);
10332 if (Meth != nullptr && Meth->isImplicit()) {
10333 CXXRecordDecl *ParentClass = Meth->getParent();
10334 Sema::CXXSpecialMember CSM;
10335
10336 switch (FnKindPair.first) {
10337 default:
10338 return;
10339 case oc_implicit_default_constructor:
10340 CSM = Sema::CXXDefaultConstructor;
10341 break;
10342 case oc_implicit_copy_constructor:
10343 CSM = Sema::CXXCopyConstructor;
10344 break;
10345 case oc_implicit_move_constructor:
10346 CSM = Sema::CXXMoveConstructor;
10347 break;
10348 case oc_implicit_copy_assignment:
10349 CSM = Sema::CXXCopyAssignment;
10350 break;
10351 case oc_implicit_move_assignment:
10352 CSM = Sema::CXXMoveAssignment;
10353 break;
10354 };
10355
10356 bool ConstRHS = false;
10357 if (Meth->getNumParams()) {
10358 if (const ReferenceType *RT =
10359 Meth->getParamDecl(0)->getType()->getAs<ReferenceType>()) {
10360 ConstRHS = RT->getPointeeType().isConstQualified();
10361 }
10362 }
10363
10364 S.inferCUDATargetForImplicitSpecialMember(ParentClass, CSM, Meth,
10365 /* ConstRHS */ ConstRHS,
10366 /* Diagnose */ true);
10367 }
10368}
10369
10370static void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
10371 FunctionDecl *Callee = Cand->Function;
10372 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
10373
10374 S.Diag(Callee->getLocation(),
10375 diag::note_ovl_candidate_disabled_by_function_cond_attr)
10376 << Attr->getCond()->getSourceRange() << Attr->getMessage();
10377}
10378
10379static void DiagnoseFailedExplicitSpec(Sema &S, OverloadCandidate *Cand) {
10380 ExplicitSpecifier ES;
10381 const char *DeclName;
10382 switch (Cand->Function->getDeclKind()) {
10383 case Decl::Kind::CXXConstructor:
10384 ES = cast<CXXConstructorDecl>(Cand->Function)->getExplicitSpecifier();
10385 DeclName = "constructor";
10386 break;
10387 case Decl::Kind::CXXConversion:
10388 ES = cast<CXXConversionDecl>(Cand->Function)->getExplicitSpecifier();
10389 DeclName = "conversion operator";
10390 break;
10391 case Decl::Kind::CXXDeductionGuide:
10392 ES = cast<CXXDeductionGuideDecl>(Cand->Function)->getExplicitSpecifier();
10393 DeclName = "deductiong guide";
10394 break;
10395 default:
10396 llvm_unreachable("invalid Decl");
10397 }
10398 assert(ES.getExpr() && "null expression should be handled before");
10399 S.Diag(Cand->Function->getLocation(),
10400 diag::note_ovl_candidate_explicit_forbidden)
10401 << DeclName;
10402 S.Diag(ES.getExpr()->getBeginLoc(),
10403 diag::note_explicit_bool_resolved_to_true);
10404}
10405
10406static void DiagnoseOpenCLExtensionDisabled(Sema &S, OverloadCandidate *Cand) {
10407 FunctionDecl *Callee = Cand->Function;
10408
10409 S.Diag(Callee->getLocation(),
10410 diag::note_ovl_candidate_disabled_by_extension)
10411 << S.getOpenCLExtensionsFromDeclExtMap(Callee);
10412}
10413
10414/// Generates a 'note' diagnostic for an overload candidate. We've
10415/// already generated a primary error at the call site.
10416///
10417/// It really does need to be a single diagnostic with its caret
10418/// pointed at the candidate declaration. Yes, this creates some
10419/// major challenges of technical writing. Yes, this makes pointing
10420/// out problems with specific arguments quite awkward. It's still
10421/// better than generating twenty screens of text for every failed
10422/// overload.
10423///
10424/// It would be great to be able to express per-candidate problems
10425/// more richly for those diagnostic clients that cared, but we'd
10426/// still have to be just as careful with the default diagnostics.
10427static void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
10428 unsigned NumArgs,
10429 bool TakingCandidateAddress) {
10430 FunctionDecl *Fn = Cand->Function;
10431
10432 // Note deleted candidates, but only if they're viable.
10433 if (Cand->Viable) {
10434 if (Fn->isDeleted()) {
10435 std::string FnDesc;
10436 std::pair<OverloadCandidateKind, OverloadCandidateSelect> FnKindPair =
10437 ClassifyOverloadCandidate(S, Cand->FoundDecl, Fn, FnDesc);
10438
10439 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
10440 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
10441 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
10442 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10443 return;
10444 }
10445
10446 // We don't really have anything else to say about viable candidates.
10447 S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10448 return;
10449 }
10450
10451 switch (Cand->FailureKind) {
10452 case ovl_fail_too_many_arguments:
10453 case ovl_fail_too_few_arguments:
10454 return DiagnoseArityMismatch(S, Cand, NumArgs);
10455
10456 case ovl_fail_bad_deduction:
10457 return DiagnoseBadDeduction(S, Cand, NumArgs,
10458 TakingCandidateAddress);
10459
10460 case ovl_fail_illegal_constructor: {
10461 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_illegal_constructor)
10462 << (Fn->getPrimaryTemplate() ? 1 : 0);
10463 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10464 return;
10465 }
10466
10467 case ovl_fail_trivial_conversion:
10468 case ovl_fail_bad_final_conversion:
10469 case ovl_fail_final_conversion_not_exact:
10470 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10471
10472 case ovl_fail_bad_conversion: {
10473 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
10474 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
10475 if (Cand->Conversions[I].isBad())
10476 return DiagnoseBadConversion(S, Cand, I, TakingCandidateAddress);
10477
10478 // FIXME: this currently happens when we're called from SemaInit
10479 // when user-conversion overload fails. Figure out how to handle
10480 // those conditions and diagnose them well.
10481 return S.NoteOverloadCandidate(Cand->FoundDecl, Fn);
10482 }
10483
10484 case ovl_fail_bad_target:
10485 return DiagnoseBadTarget(S, Cand);
10486
10487 case ovl_fail_enable_if:
10488 return DiagnoseFailedEnableIfAttr(S, Cand);
10489
10490 case ovl_fail_explicit_resolved:
10491 return DiagnoseFailedExplicitSpec(S, Cand);
10492
10493 case ovl_fail_ext_disabled:
10494 return DiagnoseOpenCLExtensionDisabled(S, Cand);
10495
10496 case ovl_fail_inhctor_slice:
10497 // It's generally not interesting to note copy/move constructors here.
10498 if (cast<CXXConstructorDecl>(Fn)->isCopyOrMoveConstructor())
10499 return;
10500 S.Diag(Fn->getLocation(),
10501 diag::note_ovl_candidate_inherited_constructor_slice)
10502 << (Fn->getPrimaryTemplate() ? 1 : 0)
10503 << Fn->getParamDecl(0)->getType()->isRValueReferenceType();
10504 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
10505 return;
10506
10507 case ovl_fail_addr_not_available: {
10508 bool Available = checkAddressOfCandidateIsAvailable(S, Cand->Function);
10509 (void)Available;
10510 assert(!Available);
10511 break;
10512 }
10513 case ovl_non_default_multiversion_function:
10514 // Do nothing, these should simply be ignored.
10515 break;
10516 }
10517}
10518
10519static void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
10520 // Desugar the type of the surrogate down to a function type,
10521 // retaining as many typedefs as possible while still showing
10522 // the function type (and, therefore, its parameter types).
10523 QualType FnType = Cand->Surrogate->getConversionType();
10524 bool isLValueReference = false;
10525 bool isRValueReference = false;
10526 bool isPointer = false;
10527 if (const LValueReferenceType *FnTypeRef =
10528 FnType->getAs<LValueReferenceType>()) {
10529 FnType = FnTypeRef->getPointeeType();
10530 isLValueReference = true;
10531 } else if (const RValueReferenceType *FnTypeRef =
10532 FnType->getAs<RValueReferenceType>()) {
10533 FnType = FnTypeRef->getPointeeType();
10534 isRValueReference = true;
10535 }
10536 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
10537 FnType = FnTypePtr->getPointeeType();
10538 isPointer = true;
10539 }
10540 // Desugar down to a function type.
10541 FnType = QualType(FnType->getAs<FunctionType>(), 0);
10542 // Reconstruct the pointer/reference as appropriate.
10543 if (isPointer) FnType = S.Context.getPointerType(FnType);
10544 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
10545 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
10546
10547 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
10548 << FnType;
10549}
10550
10551static void NoteBuiltinOperatorCandidate(Sema &S, StringRef Opc,
10552 SourceLocation OpLoc,
10553 OverloadCandidate *Cand) {
10554 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
10555 std::string TypeStr("operator");
10556 TypeStr += Opc;
10557 TypeStr += "(";
10558 TypeStr += Cand->BuiltinParamTypes[0].getAsString();
10559 if (Cand->Conversions.size() == 1) {
10560 TypeStr += ")";
10561 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
10562 } else {
10563 TypeStr += ", ";
10564 TypeStr += Cand->BuiltinParamTypes[1].getAsString();
10565 TypeStr += ")";
10566 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
10567 }
10568}
10569
10570static void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
10571 OverloadCandidate *Cand) {
10572 for (const ImplicitConversionSequence &ICS : Cand->Conversions) {
10573 if (ICS.isBad()) break; // all meaningless after first invalid
10574 if (!ICS.isAmbiguous()) continue;
10575
10576 ICS.DiagnoseAmbiguousConversion(
10577 S, OpLoc, S.PDiag(diag::note_ambiguous_type_conversion));
10578 }
10579}
10580
10581static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
10582 if (Cand->Function)
10583 return Cand->Function->getLocation();
10584 if (Cand->IsSurrogate)
10585 return Cand->Surrogate->getLocation();
10586 return SourceLocation();
10587}
10588
10589static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
10590 switch ((Sema::TemplateDeductionResult)DFI.Result) {
10591 case Sema::TDK_Success:
10592 case Sema::TDK_NonDependentConversionFailure:
10593 llvm_unreachable("non-deduction failure while diagnosing bad deduction");
10594
10595 case Sema::TDK_Invalid:
10596 case Sema::TDK_Incomplete:
10597 case Sema::TDK_IncompletePack:
10598 return 1;
10599
10600 case Sema::TDK_Underqualified:
10601 case Sema::TDK_Inconsistent:
10602 return 2;
10603
10604 case Sema::TDK_SubstitutionFailure:
10605 case Sema::TDK_DeducedMismatch:
10606 case Sema::TDK_DeducedMismatchNested:
10607 case Sema::TDK_NonDeducedMismatch:
10608 case Sema::TDK_MiscellaneousDeductionFailure:
10609 case Sema::TDK_CUDATargetMismatch:
10610 return 3;
10611
10612 case Sema::TDK_InstantiationDepth:
10613 return 4;
10614
10615 case Sema::TDK_InvalidExplicitArguments:
10616 return 5;
10617
10618 case Sema::TDK_TooManyArguments:
10619 case Sema::TDK_TooFewArguments:
10620 return 6;
10621 }
10622 llvm_unreachable("Unhandled deduction result");
10623}
10624
10625namespace {
10626struct CompareOverloadCandidatesForDisplay {
10627 Sema &S;
10628 SourceLocation Loc;
10629 size_t NumArgs;
10630 OverloadCandidateSet::CandidateSetKind CSK;
10631
10632 CompareOverloadCandidatesForDisplay(
10633 Sema &S, SourceLocation Loc, size_t NArgs,
10634 OverloadCandidateSet::CandidateSetKind CSK)
10635 : S(S), NumArgs(NArgs), CSK(CSK) {}
10636
10637 bool operator()(const OverloadCandidate *L,
10638 const OverloadCandidate *R) {
10639 // Fast-path this check.
10640 if (L == R) return false;
10641
10642 // Order first by viability.
10643 if (L->Viable) {
10644 if (!R->Viable) return true;
10645
10646 // TODO: introduce a tri-valued comparison for overload
10647 // candidates. Would be more worthwhile if we had a sort
10648 // that could exploit it.
10649 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation(), CSK))
10650 return true;
10651 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation(), CSK))
10652 return false;
10653 } else if (R->Viable)
10654 return false;
10655
10656 assert(L->Viable == R->Viable);
10657
10658 // Criteria by which we can sort non-viable candidates:
10659 if (!L->Viable) {
10660 // 1. Arity mismatches come after other candidates.
10661 if (L->FailureKind == ovl_fail_too_many_arguments ||
10662 L->FailureKind == ovl_fail_too_few_arguments) {
10663 if (R->FailureKind == ovl_fail_too_many_arguments ||
10664 R->FailureKind == ovl_fail_too_few_arguments) {
10665 int LDist = std::abs((int)L->getNumParams() - (int)NumArgs);
10666 int RDist = std::abs((int)R->getNumParams() - (int)NumArgs);
10667 if (LDist == RDist) {
10668 if (L->FailureKind == R->FailureKind)
10669 // Sort non-surrogates before surrogates.
10670 return !L->IsSurrogate && R->IsSurrogate;
10671 // Sort candidates requiring fewer parameters than there were
10672 // arguments given after candidates requiring more parameters
10673 // than there were arguments given.
10674 return L->FailureKind == ovl_fail_too_many_arguments;
10675 }
10676 return LDist < RDist;
10677 }
10678 return false;
10679 }
10680 if (R->FailureKind == ovl_fail_too_many_arguments ||
10681 R->FailureKind == ovl_fail_too_few_arguments)
10682 return true;
10683
10684 // 2. Bad conversions come first and are ordered by the number
10685 // of bad conversions and quality of good conversions.
10686 if (L->FailureKind == ovl_fail_bad_conversion) {
10687 if (R->FailureKind != ovl_fail_bad_conversion)
10688 return true;
10689
10690 // The conversion that can be fixed with a smaller number of changes,
10691 // comes first.
10692 unsigned numLFixes = L->Fix.NumConversionsFixed;
10693 unsigned numRFixes = R->Fix.NumConversionsFixed;
10694 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
10695 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
10696 if (numLFixes != numRFixes) {
10697 return numLFixes < numRFixes;
10698 }
10699
10700 // If there's any ordering between the defined conversions...
10701 // FIXME: this might not be transitive.
10702 assert(L->Conversions.size() == R->Conversions.size());
10703
10704 int leftBetter = 0;
10705 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
10706 for (unsigned E = L->Conversions.size(); I != E; ++I) {
10707 switch (CompareImplicitConversionSequences(S, Loc,
10708 L->Conversions[I],
10709 R->Conversions[I])) {
10710 case ImplicitConversionSequence::Better:
10711 leftBetter++;
10712 break;
10713
10714 case ImplicitConversionSequence::Worse:
10715 leftBetter--;
10716 break;
10717
10718 case ImplicitConversionSequence::Indistinguishable:
10719 break;
10720 }
10721 }
10722 if (leftBetter > 0) return true;
10723 if (leftBetter < 0) return false;
10724
10725 } else if (R->FailureKind == ovl_fail_bad_conversion)
10726 return false;
10727
10728 if (L->FailureKind == ovl_fail_bad_deduction) {
10729 if (R->FailureKind != ovl_fail_bad_deduction)
10730 return true;
10731
10732 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10733 return RankDeductionFailure(L->DeductionFailure)
10734 < RankDeductionFailure(R->DeductionFailure);
10735 } else if (R->FailureKind == ovl_fail_bad_deduction)
10736 return false;
10737
10738 // TODO: others?
10739 }
10740
10741 // Sort everything else by location.
10742 SourceLocation LLoc = GetLocationForCandidate(L);
10743 SourceLocation RLoc = GetLocationForCandidate(R);
10744
10745 // Put candidates without locations (e.g. builtins) at the end.
10746 if (LLoc.isInvalid()) return false;
10747 if (RLoc.isInvalid()) return true;
10748
10749 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10750 }
10751};
10752}
10753
10754/// CompleteNonViableCandidate - Normally, overload resolution only
10755/// computes up to the first bad conversion. Produces the FixIt set if
10756/// possible.
10757static void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
10758 ArrayRef<Expr *> Args) {
10759 assert(!Cand->Viable);
10760
10761 // Don't do anything on failures other than bad conversion.
10762 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
10763
10764 // We only want the FixIts if all the arguments can be corrected.
10765 bool Unfixable = false;
10766 // Use a implicit copy initialization to check conversion fixes.
10767 Cand->Fix.setConversionChecker(TryCopyInitialization);
10768
10769 // Attempt to fix the bad conversion.
10770 unsigned ConvCount = Cand->Conversions.size();
10771 for (unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0); /**/;
10772 ++ConvIdx) {
10773 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
10774 if (Cand->Conversions[ConvIdx].isInitialized() &&
10775 Cand->Conversions[ConvIdx].isBad()) {
10776 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10777 break;
10778 }
10779 }
10780
10781 // FIXME: this should probably be preserved from the overload
10782 // operation somehow.
10783 bool SuppressUserConversions = false;
10784
10785 unsigned ConvIdx = 0;
10786 ArrayRef<QualType> ParamTypes;
10787
10788 if (Cand->IsSurrogate) {
10789 QualType ConvType
10790 = Cand->Surrogate->getConversionType().getNonReferenceType();
10791 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10792 ConvType = ConvPtrType->getPointeeType();
10793 ParamTypes = ConvType->getAs<FunctionProtoType>()->getParamTypes();
10794 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10795 ConvIdx = 1;
10796 } else if (Cand->Function) {
10797 ParamTypes =
10798 Cand->Function->getType()->getAs<FunctionProtoType>()->getParamTypes();
10799 if (isa<CXXMethodDecl>(Cand->Function) &&
10800 !isa<CXXConstructorDecl>(Cand->Function)) {
10801 // Conversion 0 is 'this', which doesn't have a corresponding argument.
10802 ConvIdx = 1;
10803 }
10804 } else {
10805 // Builtin operator.
10806 assert(ConvCount <= 3);
10807 ParamTypes = Cand->BuiltinParamTypes;
10808 }
10809
10810 // Fill in the rest of the conversions.
10811 for (unsigned ArgIdx = 0; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
10812 if (Cand->Conversions[ConvIdx].isInitialized()) {
10813 // We've already checked this conversion.
10814 } else if (ArgIdx < ParamTypes.size()) {
10815 if (ParamTypes[ArgIdx]->isDependentType())
10816 Cand->Conversions[ConvIdx].setAsIdentityConversion(
10817 Args[ArgIdx]->getType());
10818 else {
10819 Cand->Conversions[ConvIdx] =
10820 TryCopyInitialization(S, Args[ArgIdx], ParamTypes[ArgIdx],
10821 SuppressUserConversions,
10822 /*InOverloadResolution=*/true,
10823 /*AllowObjCWritebackConversion=*/
10824 S.getLangOpts().ObjCAutoRefCount);
10825 // Store the FixIt in the candidate if it exists.
10826 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
10827 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
10828 }
10829 } else
10830 Cand->Conversions[ConvIdx].setEllipsis();
10831 }
10832}
10833
10834SmallVector<OverloadCandidate *, 32> OverloadCandidateSet::CompleteCandidates(
10835 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10836 SourceLocation OpLoc,
10837 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10838 // Sort the candidates by viability and position. Sorting directly would
10839 // be prohibitive, so we make a set of pointers and sort those.
10840 SmallVector<OverloadCandidate*, 32> Cands;
10841 if (OCD == OCD_AllCandidates) Cands.reserve(size());
10842 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10843 if (!Filter(*Cand))
10844 continue;
10845 if (Cand->Viable)
10846 Cands.push_back(Cand);
10847 else if (OCD == OCD_AllCandidates) {
10848 CompleteNonViableCandidate(S, Cand, Args);
10849 if (Cand->Function || Cand->IsSurrogate)
10850 Cands.push_back(Cand);
10851 // Otherwise, this a non-viable builtin candidate. We do not, in general,
10852 // want to list every possible builtin candidate.
10853 }
10854 }
10855
10856 llvm::stable_sort(
10857 Cands, CompareOverloadCandidatesForDisplay(S, OpLoc, Args.size(), Kind));
10858
10859 return Cands;
10860}
10861
10862/// When overload resolution fails, prints diagnostic messages containing the
10863/// candidates in the candidate set.
10864void OverloadCandidateSet::NoteCandidates(PartialDiagnosticAt PD,
10865 Sema &S, OverloadCandidateDisplayKind OCD, ArrayRef<Expr *> Args,
10866 StringRef Opc, SourceLocation OpLoc,
10867 llvm::function_ref<bool(OverloadCandidate &)> Filter) {
10868
10869 auto Cands = CompleteCandidates(S, OCD, Args, OpLoc, Filter);
10870
10871 S.Diag(PD.first, PD.second);
10872
10873 NoteCandidates(S, Args, Cands, Opc, OpLoc);
10874}
10875
10876void OverloadCandidateSet::NoteCandidates(Sema &S, ArrayRef<Expr *> Args,
10877 ArrayRef<OverloadCandidate *> Cands,
10878 StringRef Opc, SourceLocation OpLoc) {
10879 bool ReportedAmbiguousConversions = false;
10880
10881 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
10882 unsigned CandsShown = 0;
10883 auto I = Cands.begin(), E = Cands.end();
10884 for (; I != E; ++I) {
10885 OverloadCandidate *Cand = *I;
10886
10887 // Set an arbitrary limit on the number of candidate functions we'll spam
10888 // the user with. FIXME: This limit should depend on details of the
10889 // candidate list.
10890 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
10891 break;
10892 }
10893 ++CandsShown;
10894
10895 if (Cand->Function)
10896 NoteFunctionCandidate(S, Cand, Args.size(),
10897 /*TakingCandidateAddress=*/false);
10898 else if (Cand->IsSurrogate)
10899 NoteSurrogateCandidate(S, Cand);
10900 else {
10901 assert(Cand->Viable &&
10902 "Non-viable built-in candidates are not added to Cands.");
10903 // Generally we only see ambiguities including viable builtin
10904 // operators if overload resolution got screwed up by an
10905 // ambiguous user-defined conversion.
10906 //
10907 // FIXME: It's quite possible for different conversions to see
10908 // different ambiguities, though.
10909 if (!ReportedAmbiguousConversions) {
10910 NoteAmbiguousUserConversions(S, OpLoc, Cand);
10911 ReportedAmbiguousConversions = true;
10912 }
10913
10914 // If this is a viable builtin, print it.
10915 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
10916 }
10917 }
10918
10919 if (I != E)
10920 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
10921}
10922
10923static SourceLocation
10924GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
10925 return Cand->Specialization ? Cand->Specialization->getLocation()
10926 : SourceLocation();
10927}
10928
10929namespace {
10930struct CompareTemplateSpecCandidatesForDisplay {
10931 Sema &S;
10932 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
10933
10934 bool operator()(const TemplateSpecCandidate *L,
10935 const TemplateSpecCandidate *R) {
10936 // Fast-path this check.
10937 if (L == R)
10938 return false;
10939
10940 // Assuming that both candidates are not matches...
10941
10942 // Sort by the ranking of deduction failures.
10943 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
10944 return RankDeductionFailure(L->DeductionFailure) <
10945 RankDeductionFailure(R->DeductionFailure);
10946
10947 // Sort everything else by location.
10948 SourceLocation LLoc = GetLocationForCandidate(L);
10949 SourceLocation RLoc = GetLocationForCandidate(R);
10950
10951 // Put candidates without locations (e.g. builtins) at the end.
10952 if (LLoc.isInvalid())
10953 return false;
10954 if (RLoc.isInvalid())
10955 return true;
10956
10957 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
10958 }
10959};
10960}
10961
10962/// Diagnose a template argument deduction failure.
10963/// We are treating these failures as overload failures due to bad
10964/// deductions.
10965void TemplateSpecCandidate::NoteDeductionFailure(Sema &S,
10966 bool ForTakingAddress) {
10967 DiagnoseBadDeduction(S, FoundDecl, Specialization, // pattern
10968 DeductionFailure, /*NumArgs=*/0, ForTakingAddress);
10969}
10970
10971void TemplateSpecCandidateSet::destroyCandidates() {
10972 for (iterator i = begin(), e = end(); i != e; ++i) {
10973 i->DeductionFailure.Destroy();
10974 }
10975}
10976
10977void TemplateSpecCandidateSet::clear() {
10978 destroyCandidates();
10979 Candidates.clear();
10980}
10981
10982/// NoteCandidates - When no template specialization match is found, prints
10983/// diagnostic messages containing the non-matching specializations that form
10984/// the candidate set.
10985/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
10986/// OCD == OCD_AllCandidates and Cand->Viable == false.
10987void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
10988 // Sort the candidates by position (assuming no candidate is a match).
10989 // Sorting directly would be prohibitive, so we make a set of pointers
10990 // and sort those.
10991 SmallVector<TemplateSpecCandidate *, 32> Cands;
10992 Cands.reserve(size());
10993 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
10994 if (Cand->Specialization)
10995 Cands.push_back(Cand);
10996 // Otherwise, this is a non-matching builtin candidate. We do not,
10997 // in general, want to list every possible builtin candidate.
10998 }
10999
11000 llvm::sort(Cands, CompareTemplateSpecCandidatesForDisplay(S));
11001
11002 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
11003 // for generalization purposes (?).
11004 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
11005
11006 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
11007 unsigned CandsShown = 0;
11008 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
11009 TemplateSpecCandidate *Cand = *I;
11010
11011 // Set an arbitrary limit on the number of candidates we'll spam
11012 // the user with. FIXME: This limit should depend on details of the
11013 // candidate list.
11014 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
11015 break;
11016 ++CandsShown;
11017
11018 assert(Cand->Specialization &&
11019 "Non-matching built-in candidates are not added to Cands.");
11020 Cand->NoteDeductionFailure(S, ForTakingAddress);
11021 }
11022
11023 if (I != E)
11024 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
11025}
11026
11027// [PossiblyAFunctionType] --> [Return]
11028// NonFunctionType --> NonFunctionType
11029// R (A) --> R(A)
11030// R (*)(A) --> R (A)
11031// R (&)(A) --> R (A)
11032// R (S::*)(A) --> R (A)
11033QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
11034 QualType Ret = PossiblyAFunctionType;
11035 if (const PointerType *ToTypePtr =
11036 PossiblyAFunctionType->getAs<PointerType>())
11037 Ret = ToTypePtr->getPointeeType();
11038 else if (const ReferenceType *ToTypeRef =
11039 PossiblyAFunctionType->getAs<ReferenceType>())
11040 Ret = ToTypeRef->getPointeeType();
11041 else if (const MemberPointerType *MemTypePtr =
11042 PossiblyAFunctionType->getAs<MemberPointerType>())
11043 Ret = MemTypePtr->getPointeeType();
11044 Ret =
11045 Context.getCanonicalType(Ret).getUnqualifiedType();
11046 return Ret;
11047}
11048
11049static bool completeFunctionType(Sema &S, FunctionDecl *FD, SourceLocation Loc,
11050 bool Complain = true) {
11051 if (S.getLangOpts().CPlusPlus14 && FD->getReturnType()->isUndeducedType() &&
11052 S.DeduceReturnType(FD, Loc, Complain))
11053 return true;
11054
11055 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
11056 if (S.getLangOpts().CPlusPlus17 &&
11057 isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
11058 !S.ResolveExceptionSpec(Loc, FPT))
11059 return true;
11060
11061 return false;
11062}
11063
11064namespace {
11065// A helper class to help with address of function resolution
11066// - allows us to avoid passing around all those ugly parameters
11067class AddressOfFunctionResolver {
11068 Sema& S;
11069 Expr* SourceExpr;
11070 const QualType& TargetType;
11071 QualType TargetFunctionType; // Extracted function type from target type
11072
11073 bool Complain;
11074 //DeclAccessPair& ResultFunctionAccessPair;
11075 ASTContext& Context;
11076
11077 bool TargetTypeIsNonStaticMemberFunction;
11078 bool FoundNonTemplateFunction;
11079 bool StaticMemberFunctionFromBoundPointer;
11080 bool HasComplained;
11081
11082 OverloadExpr::FindResult OvlExprInfo;
11083 OverloadExpr *OvlExpr;
11084 TemplateArgumentListInfo OvlExplicitTemplateArgs;
11085 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
11086 TemplateSpecCandidateSet FailedCandidates;
11087
11088public:
11089 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
11090 const QualType &TargetType, bool Complain)
11091 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
11092 Complain(Complain), Context(S.getASTContext()),
11093 TargetTypeIsNonStaticMemberFunction(
11094 !!TargetType->getAs<MemberPointerType>()),
11095 FoundNonTemplateFunction(false),
11096 StaticMemberFunctionFromBoundPointer(false),
11097 HasComplained(false),
11098 OvlExprInfo(OverloadExpr::find(SourceExpr)),
11099 OvlExpr(OvlExprInfo.Expression),
11100 FailedCandidates(OvlExpr->getNameLoc(), /*ForTakingAddress=*/true) {
11101 ExtractUnqualifiedFunctionTypeFromTargetType();
11102
11103 if (TargetFunctionType->isFunctionType()) {
11104 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
11105 if (!UME->isImplicitAccess() &&
11106 !S.ResolveSingleFunctionTemplateSpecialization(UME))
11107 StaticMemberFunctionFromBoundPointer = true;
11108 } else if (OvlExpr->hasExplicitTemplateArgs()) {
11109 DeclAccessPair dap;
11110 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
11111 OvlExpr, false, &dap)) {
11112 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
11113 if (!Method->isStatic()) {
11114 // If the target type is a non-function type and the function found
11115 // is a non-static member function, pretend as if that was the
11116 // target, it's the only possible type to end up with.
11117 TargetTypeIsNonStaticMemberFunction = true;
11118
11119 // And skip adding the function if its not in the proper form.
11120 // We'll diagnose this due to an empty set of functions.
11121 if (!OvlExprInfo.HasFormOfMemberPointer)
11122 return;
11123 }
11124
11125 Matches.push_back(std::make_pair(dap, Fn));
11126 }
11127 return;
11128 }
11129
11130 if (OvlExpr->hasExplicitTemplateArgs())
11131 OvlExpr->copyTemplateArgumentsInto(OvlExplicitTemplateArgs);
11132
11133 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
11134 // C++ [over.over]p4:
11135 // If more than one function is selected, [...]
11136 if (Matches.size() > 1 && !eliminiateSuboptimalOverloadCandidates()) {
11137 if (FoundNonTemplateFunction)
11138 EliminateAllTemplateMatches();
11139 else
11140 EliminateAllExceptMostSpecializedTemplate();
11141 }
11142 }
11143
11144 if (S.getLangOpts().CUDA && Matches.size() > 1)
11145 EliminateSuboptimalCudaMatches();
11146 }
11147
11148 bool hasComplained() const { return HasComplained; }
11149
11150private:
11151 bool candidateHasExactlyCorrectType(const FunctionDecl *FD) {
11152 QualType Discard;
11153 return Context.hasSameUnqualifiedType(TargetFunctionType, FD->getType()) ||
11154 S.IsFunctionConversion(FD->getType(), TargetFunctionType, Discard);
11155 }
11156
11157 /// \return true if A is considered a better overload candidate for the
11158 /// desired type than B.
11159 bool isBetterCandidate(const FunctionDecl *A, const FunctionDecl *B) {
11160 // If A doesn't have exactly the correct type, we don't want to classify it
11161 // as "better" than anything else. This way, the user is required to
11162 // disambiguate for us if there are multiple candidates and no exact match.
11163 return candidateHasExactlyCorrectType(A) &&
11164 (!candidateHasExactlyCorrectType(B) ||
11165 compareEnableIfAttrs(S, A, B) == Comparison::Better);
11166 }
11167
11168 /// \return true if we were able to eliminate all but one overload candidate,
11169 /// false otherwise.
11170 bool eliminiateSuboptimalOverloadCandidates() {
11171 // Same algorithm as overload resolution -- one pass to pick the "best",
11172 // another pass to be sure that nothing is better than the best.
11173 auto Best = Matches.begin();
11174 for (auto I = Matches.begin()+1, E = Matches.end(); I != E; ++I)
11175 if (isBetterCandidate(I->second, Best->second))
11176 Best = I;
11177
11178 const FunctionDecl *BestFn = Best->second;
11179 auto IsBestOrInferiorToBest = [this, BestFn](
11180 const std::pair<DeclAccessPair, FunctionDecl *> &Pair) {
11181 return BestFn == Pair.second || isBetterCandidate(BestFn, Pair.second);
11182 };
11183
11184 // Note: We explicitly leave Matches unmodified if there isn't a clear best
11185 // option, so we can potentially give the user a better error
11186 if (!llvm::all_of(Matches, IsBestOrInferiorToBest))
11187 return false;
11188 Matches[0] = *Best;
11189 Matches.resize(1);
11190 return true;
11191 }
11192
11193 bool isTargetTypeAFunction() const {
11194 return TargetFunctionType->isFunctionType();
11195 }
11196
11197 // [ToType] [Return]
11198
11199 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
11200 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
11201 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
11202 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
11203 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
11204 }
11205
11206 // return true if any matching specializations were found
11207 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
11208 const DeclAccessPair& CurAccessFunPair) {
11209 if (CXXMethodDecl *Method
11210 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
11211 // Skip non-static function templates when converting to pointer, and
11212 // static when converting to member pointer.
11213 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11214 return false;
11215 }
11216 else if (TargetTypeIsNonStaticMemberFunction)
11217 return false;
11218
11219 // C++ [over.over]p2:
11220 // If the name is a function template, template argument deduction is
11221 // done (14.8.2.2), and if the argument deduction succeeds, the
11222 // resulting template argument list is used to generate a single
11223 // function template specialization, which is added to the set of
11224 // overloaded functions considered.
11225 FunctionDecl *Specialization = nullptr;
11226 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11227 if (Sema::TemplateDeductionResult Result
11228 = S.DeduceTemplateArguments(FunctionTemplate,
11229 &OvlExplicitTemplateArgs,
11230 TargetFunctionType, Specialization,
11231 Info, /*IsAddressOfFunction*/true)) {
11232 // Make a note of the failed deduction for diagnostics.
11233 FailedCandidates.addCandidate()
11234 .set(CurAccessFunPair, FunctionTemplate->getTemplatedDecl(),
11235 MakeDeductionFailureInfo(Context, Result, Info));
11236 return false;
11237 }
11238
11239 // Template argument deduction ensures that we have an exact match or
11240 // compatible pointer-to-function arguments that would be adjusted by ICS.
11241 // This function template specicalization works.
11242 assert(S.isSameOrCompatibleFunctionType(
11243 Context.getCanonicalType(Specialization->getType()),
11244 Context.getCanonicalType(TargetFunctionType)));
11245
11246 if (!S.checkAddressOfFunctionIsAvailable(Specialization))
11247 return false;
11248
11249 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
11250 return true;
11251 }
11252
11253 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
11254 const DeclAccessPair& CurAccessFunPair) {
11255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11256 // Skip non-static functions when converting to pointer, and static
11257 // when converting to member pointer.
11258 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
11259 return false;
11260 }
11261 else if (TargetTypeIsNonStaticMemberFunction)
11262 return false;
11263
11264 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
11265 if (S.getLangOpts().CUDA)
11266 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
11267 if (!Caller->isImplicit() && !S.IsAllowedCUDACall(Caller, FunDecl))
11268 return false;
11269 if (FunDecl->isMultiVersion()) {
11270 const auto *TA = FunDecl->getAttr<TargetAttr>();
11271 if (TA && !TA->isDefaultVersion())
11272 return false;
11273 }
11274
11275 // If any candidate has a placeholder return type, trigger its deduction
11276 // now.
11277 if (completeFunctionType(S, FunDecl, SourceExpr->getBeginLoc(),
11278 Complain)) {
11279 HasComplained |= Complain;
11280 return false;
11281 }
11282
11283 if (!S.checkAddressOfFunctionIsAvailable(FunDecl))
11284 return false;
11285
11286 // If we're in C, we need to support types that aren't exactly identical.
11287 if (!S.getLangOpts().CPlusPlus ||
11288 candidateHasExactlyCorrectType(FunDecl)) {
11289 Matches.push_back(std::make_pair(
11290 CurAccessFunPair, cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
11291 FoundNonTemplateFunction = true;
11292 return true;
11293 }
11294 }
11295
11296 return false;
11297 }
11298
11299 bool FindAllFunctionsThatMatchTargetTypeExactly() {
11300 bool Ret = false;
11301
11302 // If the overload expression doesn't have the form of a pointer to
11303 // member, don't try to convert it to a pointer-to-member type.
11304 if (IsInvalidFormOfPointerToMemberFunction())
11305 return false;
11306
11307 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11308 E = OvlExpr->decls_end();
11309 I != E; ++I) {
11310 // Look through any using declarations to find the underlying function.
11311 NamedDecl *Fn = (*I)->getUnderlyingDecl();
11312
11313 // C++ [over.over]p3:
11314 // Non-member functions and static member functions match
11315 // targets of type "pointer-to-function" or "reference-to-function."
11316 // Nonstatic member functions match targets of
11317 // type "pointer-to-member-function."
11318 // Note that according to DR 247, the containing class does not matter.
11319 if (FunctionTemplateDecl *FunctionTemplate
11320 = dyn_cast<FunctionTemplateDecl>(Fn)) {
11321 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
11322 Ret = true;
11323 }
11324 // If we have explicit template arguments supplied, skip non-templates.
11325 else if (!OvlExpr->hasExplicitTemplateArgs() &&
11326 AddMatchingNonTemplateFunction(Fn, I.getPair()))
11327 Ret = true;
11328 }
11329 assert(Ret || Matches.empty());
11330 return Ret;
11331 }
11332
11333 void EliminateAllExceptMostSpecializedTemplate() {
11334 // [...] and any given function template specialization F1 is
11335 // eliminated if the set contains a second function template
11336 // specialization whose function template is more specialized
11337 // than the function template of F1 according to the partial
11338 // ordering rules of 14.5.5.2.
11339
11340 // The algorithm specified above is quadratic. We instead use a
11341 // two-pass algorithm (similar to the one used to identify the
11342 // best viable function in an overload set) that identifies the
11343 // best function template (if it exists).
11344
11345 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
11346 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
11347 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
11348
11349 // TODO: It looks like FailedCandidates does not serve much purpose
11350 // here, since the no_viable diagnostic has index 0.
11351 UnresolvedSetIterator Result = S.getMostSpecialized(
11352 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
11353 SourceExpr->getBeginLoc(), S.PDiag(),
11354 S.PDiag(diag::err_addr_ovl_ambiguous)
11355 << Matches[0].second->getDeclName(),
11356 S.PDiag(diag::note_ovl_candidate)
11357 << (unsigned)oc_function << (unsigned)ocs_described_template,
11358 Complain, TargetFunctionType);
11359
11360 if (Result != MatchesCopy.end()) {
11361 // Make it the first and only element
11362 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
11363 Matches[0].second = cast<FunctionDecl>(*Result);
11364 Matches.resize(1);
11365 } else
11366 HasComplained |= Complain;
11367 }
11368
11369 void EliminateAllTemplateMatches() {
11370 // [...] any function template specializations in the set are
11371 // eliminated if the set also contains a non-template function, [...]
11372 for (unsigned I = 0, N = Matches.size(); I != N; ) {
11373 if (Matches[I].second->getPrimaryTemplate() == nullptr)
11374 ++I;
11375 else {
11376 Matches[I] = Matches[--N];
11377 Matches.resize(N);
11378 }
11379 }
11380 }
11381
11382 void EliminateSuboptimalCudaMatches() {
11383 S.EraseUnwantedCUDAMatches(dyn_cast<FunctionDecl>(S.CurContext), Matches);
11384 }
11385
11386public:
11387 void ComplainNoMatchesFound() const {
11388 assert(Matches.empty());
11389 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_no_viable)
11390 << OvlExpr->getName() << TargetFunctionType
11391 << OvlExpr->getSourceRange();
11392 if (FailedCandidates.empty())
11393 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11394 /*TakingAddress=*/true);
11395 else {
11396 // We have some deduction failure messages. Use them to diagnose
11397 // the function templates, and diagnose the non-template candidates
11398 // normally.
11399 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
11400 IEnd = OvlExpr->decls_end();
11401 I != IEnd; ++I)
11402 if (FunctionDecl *Fun =
11403 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
11404 if (!functionHasPassObjectSizeParams(Fun))
11405 S.NoteOverloadCandidate(*I, Fun, TargetFunctionType,
11406 /*TakingAddress=*/true);
11407 FailedCandidates.NoteCandidates(S, OvlExpr->getBeginLoc());
11408 }
11409 }
11410
11411 bool IsInvalidFormOfPointerToMemberFunction() const {
11412 return TargetTypeIsNonStaticMemberFunction &&
11413 !OvlExprInfo.HasFormOfMemberPointer;
11414 }
11415
11416 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
11417 // TODO: Should we condition this on whether any functions might
11418 // have matched, or is it more appropriate to do that in callers?
11419 // TODO: a fixit wouldn't hurt.
11420 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
11421 << TargetType << OvlExpr->getSourceRange();
11422 }
11423
11424 bool IsStaticMemberFunctionFromBoundPointer() const {
11425 return StaticMemberFunctionFromBoundPointer;
11426 }
11427
11428 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
11429 S.Diag(OvlExpr->getBeginLoc(),
11430 diag::err_invalid_form_pointer_member_function)
11431 << OvlExpr->getSourceRange();
11432 }
11433
11434 void ComplainOfInvalidConversion() const {
11435 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_not_func_ptrref)
11436 << OvlExpr->getName() << TargetType;
11437 }
11438
11439 void ComplainMultipleMatchesFound() const {
11440 assert(Matches.size() > 1);
11441 S.Diag(OvlExpr->getBeginLoc(), diag::err_addr_ovl_ambiguous)
11442 << OvlExpr->getName() << OvlExpr->getSourceRange();
11443 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType,
11444 /*TakingAddress=*/true);
11445 }
11446
11447 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
11448
11449 int getNumMatches() const { return Matches.size(); }
11450
11451 FunctionDecl* getMatchingFunctionDecl() const {
11452 if (Matches.size() != 1) return nullptr;
11453 return Matches[0].second;
11454 }
11455
11456 const DeclAccessPair* getMatchingFunctionAccessPair() const {
11457 if (Matches.size() != 1) return nullptr;
11458 return &Matches[0].first;
11459 }
11460};
11461}
11462
11463/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
11464/// an overloaded function (C++ [over.over]), where @p From is an
11465/// expression with overloaded function type and @p ToType is the type
11466/// we're trying to resolve to. For example:
11467///
11468/// @code
11469/// int f(double);
11470/// int f(int);
11471///
11472/// int (*pfd)(double) = f; // selects f(double)
11473/// @endcode
11474///
11475/// This routine returns the resulting FunctionDecl if it could be
11476/// resolved, and NULL otherwise. When @p Complain is true, this
11477/// routine will emit diagnostics if there is an error.
11478FunctionDecl *
11479Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
11480 QualType TargetType,
11481 bool Complain,
11482 DeclAccessPair &FoundResult,
11483 bool *pHadMultipleCandidates) {
11484 assert(AddressOfExpr->getType() == Context.OverloadTy);
11485
11486 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
11487 Complain);
11488 int NumMatches = Resolver.getNumMatches();
11489 FunctionDecl *Fn = nullptr;
11490 bool ShouldComplain = Complain && !Resolver.hasComplained();
11491 if (NumMatches == 0 && ShouldComplain) {
11492 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
11493 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
11494 else
11495 Resolver.ComplainNoMatchesFound();
11496 }
11497 else if (NumMatches > 1 && ShouldComplain)
11498 Resolver.ComplainMultipleMatchesFound();
11499 else if (NumMatches == 1) {
11500 Fn = Resolver.getMatchingFunctionDecl();
11501 assert(Fn);
11502 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
11503 ResolveExceptionSpec(AddressOfExpr->getExprLoc(), FPT);
11504 FoundResult = *Resolver.getMatchingFunctionAccessPair();
11505 if (Complain) {
11506 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
11507 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
11508 else
11509 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
11510 }
11511 }
11512
11513 if (pHadMultipleCandidates)
11514 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
11515 return Fn;
11516}
11517
11518/// Given an expression that refers to an overloaded function, try to
11519/// resolve that function to a single function that can have its address taken.
11520/// This will modify `Pair` iff it returns non-null.
11521///
11522/// This routine can only realistically succeed if all but one candidates in the
11523/// overload set for SrcExpr cannot have their addresses taken.
11524FunctionDecl *
11525Sema::resolveAddressOfOnlyViableOverloadCandidate(Expr *E,
11526 DeclAccessPair &Pair) {
11527 OverloadExpr::FindResult R = OverloadExpr::find(E);
11528 OverloadExpr *Ovl = R.Expression;
11529 FunctionDecl *Result = nullptr;
11530 DeclAccessPair DAP;
11531 // Don't use the AddressOfResolver because we're specifically looking for
11532 // cases where we have one overload candidate that lacks
11533 // enable_if/pass_object_size/...
11534 for (auto I = Ovl->decls_begin(), E = Ovl->decls_end(); I != E; ++I) {
11535 auto *FD = dyn_cast<FunctionDecl>(I->getUnderlyingDecl());
11536 if (!FD)
11537 return nullptr;
11538
11539 if (!checkAddressOfFunctionIsAvailable(FD))
11540 continue;
11541
11542 // We have more than one result; quit.
11543 if (Result)
11544 return nullptr;
11545 DAP = I.getPair();
11546 Result = FD;
11547 }
11548
11549 if (Result)
11550 Pair = DAP;
11551 return Result;
11552}
11553
11554/// Given an overloaded function, tries to turn it into a non-overloaded
11555/// function reference using resolveAddressOfOnlyViableOverloadCandidate. This
11556/// will perform access checks, diagnose the use of the resultant decl, and, if
11557/// requested, potentially perform a function-to-pointer decay.
11558///
11559/// Returns false if resolveAddressOfOnlyViableOverloadCandidate fails.
11560/// Otherwise, returns true. This may emit diagnostics and return true.
11561bool Sema::resolveAndFixAddressOfOnlyViableOverloadCandidate(
11562 ExprResult &SrcExpr, bool DoFunctionPointerConverion) {
11563 Expr *E = SrcExpr.get();
11564 assert(E->getType() == Context.OverloadTy && "SrcExpr must be an overload");
11565
11566 DeclAccessPair DAP;
11567 FunctionDecl *Found = resolveAddressOfOnlyViableOverloadCandidate(E, DAP);
11568 if (!Found || Found->isCPUDispatchMultiVersion() ||
11569 Found->isCPUSpecificMultiVersion())
11570 return false;
11571
11572 // Emitting multiple diagnostics for a function that is both inaccessible and
11573 // unavailable is consistent with our behavior elsewhere. So, always check
11574 // for both.
11575 DiagnoseUseOfDecl(Found, E->getExprLoc());
11576 CheckAddressOfMemberAccess(E, DAP);
11577 Expr *Fixed = FixOverloadedFunctionReference(E, DAP, Found);
11578 if (DoFunctionPointerConverion && Fixed->getType()->isFunctionType())
11579 SrcExpr = DefaultFunctionArrayConversion(Fixed, /*Diagnose=*/false);
11580 else
11581 SrcExpr = Fixed;
11582 return true;
11583}
11584
11585/// Given an expression that refers to an overloaded function, try to
11586/// resolve that overloaded function expression down to a single function.
11587///
11588/// This routine can only resolve template-ids that refer to a single function
11589/// template, where that template-id refers to a single template whose template
11590/// arguments are either provided by the template-id or have defaults,
11591/// as described in C++0x [temp.arg.explicit]p3.
11592///
11593/// If no template-ids are found, no diagnostics are emitted and NULL is
11594/// returned.
11595FunctionDecl *
11596Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
11597 bool Complain,
11598 DeclAccessPair *FoundResult) {
11599 // C++ [over.over]p1:
11600 // [...] [Note: any redundant set of parentheses surrounding the
11601 // overloaded function name is ignored (5.1). ]
11602 // C++ [over.over]p1:
11603 // [...] The overloaded function name can be preceded by the &
11604 // operator.
11605
11606 // If we didn't actually find any template-ids, we're done.
11607 if (!ovl->hasExplicitTemplateArgs())
11608 return nullptr;
11609
11610 TemplateArgumentListInfo ExplicitTemplateArgs;
11611 ovl->copyTemplateArgumentsInto(ExplicitTemplateArgs);
11612 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
11613
11614 // Look through all of the overloaded functions, searching for one
11615 // whose type matches exactly.
11616 FunctionDecl *Matched = nullptr;
11617 for (UnresolvedSetIterator I = ovl->decls_begin(),
11618 E = ovl->decls_end(); I != E; ++I) {
11619 // C++0x [temp.arg.explicit]p3:
11620 // [...] In contexts where deduction is done and fails, or in contexts
11621 // where deduction is not done, if a template argument list is
11622 // specified and it, along with any default template arguments,
11623 // identifies a single function template specialization, then the
11624 // template-id is an lvalue for the function template specialization.
11625 FunctionTemplateDecl *FunctionTemplate
11626 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
11627
11628 // C++ [over.over]p2:
11629 // If the name is a function template, template argument deduction is
11630 // done (14.8.2.2), and if the argument deduction succeeds, the
11631 // resulting template argument list is used to generate a single
11632 // function template specialization, which is added to the set of
11633 // overloaded functions considered.
11634 FunctionDecl *Specialization = nullptr;
11635 TemplateDeductionInfo Info(FailedCandidates.getLocation());
11636 if (TemplateDeductionResult Result
11637 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
11638 Specialization, Info,
11639 /*IsAddressOfFunction*/true)) {
11640 // Make a note of the failed deduction for diagnostics.
11641 // TODO: Actually use the failed-deduction info?
11642 FailedCandidates.addCandidate()
11643 .set(I.getPair(), FunctionTemplate->getTemplatedDecl(),
11644 MakeDeductionFailureInfo(Context, Result, Info));
11645 continue;
11646 }
11647
11648 assert(Specialization && "no specialization and no error?");
11649
11650 // Multiple matches; we can't resolve to a single declaration.
11651 if (Matched) {
11652 if (Complain) {
11653 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
11654 << ovl->getName();
11655 NoteAllOverloadCandidates(ovl);
11656 }
11657 return nullptr;
11658 }
11659
11660 Matched = Specialization;
11661 if (FoundResult) *FoundResult = I.getPair();
11662 }
11663
11664 if (Matched &&
11665 completeFunctionType(*this, Matched, ovl->getExprLoc(), Complain))
11666 return nullptr;
11667
11668 return Matched;
11669}
11670
11671// Resolve and fix an overloaded expression that can be resolved
11672// because it identifies a single function template specialization.
11673//
11674// Last three arguments should only be supplied if Complain = true
11675//
11676// Return true if it was logically possible to so resolve the
11677// expression, regardless of whether or not it succeeded. Always
11678// returns true if 'complain' is set.
11679bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
11680 ExprResult &SrcExpr, bool doFunctionPointerConverion,
11681 bool complain, SourceRange OpRangeForComplaining,
11682 QualType DestTypeForComplaining,
11683 unsigned DiagIDForComplaining) {
11684 assert(SrcExpr.get()->getType() == Context.OverloadTy);
11685
11686 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
11687
11688 DeclAccessPair found;
11689 ExprResult SingleFunctionExpression;
11690 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
11691 ovl.Expression, /*complain*/ false, &found)) {
11692 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getBeginLoc())) {
11693 SrcExpr = ExprError();
11694 return true;
11695 }
11696
11697 // It is only correct to resolve to an instance method if we're
11698 // resolving a form that's permitted to be a pointer to member.
11699 // Otherwise we'll end up making a bound member expression, which
11700 // is illegal in all the contexts we resolve like this.
11701 if (!ovl.HasFormOfMemberPointer &&
11702 isa<CXXMethodDecl>(fn) &&
11703 cast<CXXMethodDecl>(fn)->isInstance()) {
11704 if (!complain) return false;
11705
11706 Diag(ovl.Expression->getExprLoc(),
11707 diag::err_bound_member_function)
11708 << 0 << ovl.Expression->getSourceRange();
11709
11710 // TODO: I believe we only end up here if there's a mix of
11711 // static and non-static candidates (otherwise the expression
11712 // would have 'bound member' type, not 'overload' type).
11713 // Ideally we would note which candidate was chosen and why
11714 // the static candidates were rejected.
11715 SrcExpr = ExprError();
11716 return true;
11717 }
11718
11719 // Fix the expression to refer to 'fn'.
11720 SingleFunctionExpression =
11721 FixOverloadedFunctionReference(SrcExpr.get(), found, fn);
11722
11723 // If desired, do function-to-pointer decay.
11724 if (doFunctionPointerConverion) {
11725 SingleFunctionExpression =
11726 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.get());
11727 if (SingleFunctionExpression.isInvalid()) {
11728 SrcExpr = ExprError();
11729 return true;
11730 }
11731 }
11732 }
11733
11734 if (!SingleFunctionExpression.isUsable()) {
11735 if (complain) {
11736 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
11737 << ovl.Expression->getName()
11738 << DestTypeForComplaining
11739 << OpRangeForComplaining
11740 << ovl.Expression->getQualifierLoc().getSourceRange();
11741 NoteAllOverloadCandidates(SrcExpr.get());
11742
11743 SrcExpr = ExprError();
11744 return true;
11745 }
11746
11747 return false;
11748 }
11749
11750 SrcExpr = SingleFunctionExpression;
11751 return true;
11752}
11753
11754/// Add a single candidate to the overload set.
11755static void AddOverloadedCallCandidate(Sema &S,
11756 DeclAccessPair FoundDecl,
11757 TemplateArgumentListInfo *ExplicitTemplateArgs,
11758 ArrayRef<Expr *> Args,
11759 OverloadCandidateSet &CandidateSet,
11760 bool PartialOverloading,
11761 bool KnownValid) {
11762 NamedDecl *Callee = FoundDecl.getDecl();
11763 if (isa<UsingShadowDecl>(Callee))
11764 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
11765
11766 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
11767 if (ExplicitTemplateArgs) {
11768 assert(!KnownValid && "Explicit template arguments?");
11769 return;
11770 }
11771 // Prevent ill-formed function decls to be added as overload candidates.
11772 if (!dyn_cast<FunctionProtoType>(Func->getType()->getAs<FunctionType>()))
11773 return;
11774
11775 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet,
11776 /*SuppressUsedConversions=*/false,
11777 PartialOverloading);
11778 return;
11779 }
11780
11781 if (FunctionTemplateDecl *FuncTemplate
11782 = dyn_cast<FunctionTemplateDecl>(Callee)) {
11783 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
11784 ExplicitTemplateArgs, Args, CandidateSet,
11785 /*SuppressUsedConversions=*/false,
11786 PartialOverloading);
11787 return;
11788 }
11789
11790 assert(!KnownValid && "unhandled case in overloaded call candidate");
11791}
11792
11793/// Add the overload candidates named by callee and/or found by argument
11794/// dependent lookup to the given overload set.
11795void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
11796 ArrayRef<Expr *> Args,
11797 OverloadCandidateSet &CandidateSet,
11798 bool PartialOverloading) {
11799
11800#ifndef NDEBUG
11801 // Verify that ArgumentDependentLookup is consistent with the rules
11802 // in C++0x [basic.lookup.argdep]p3:
11803 //
11804 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11805 // and let Y be the lookup set produced by argument dependent
11806 // lookup (defined as follows). If X contains
11807 //
11808 // -- a declaration of a class member, or
11809 //
11810 // -- a block-scope function declaration that is not a
11811 // using-declaration, or
11812 //
11813 // -- a declaration that is neither a function or a function
11814 // template
11815 //
11816 // then Y is empty.
11817
11818 if (ULE->requiresADL()) {
11819 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11820 E = ULE->decls_end(); I != E; ++I) {
11821 assert(!(*I)->getDeclContext()->isRecord());
11822 assert(isa<UsingShadowDecl>(*I) ||
11823 !(*I)->getDeclContext()->isFunctionOrMethod());
11824 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
11825 }
11826 }
11827#endif
11828
11829 // It would be nice to avoid this copy.
11830 TemplateArgumentListInfo TABuffer;
11831 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
11832 if (ULE->hasExplicitTemplateArgs()) {
11833 ULE->copyTemplateArgumentsInto(TABuffer);
11834 ExplicitTemplateArgs = &TABuffer;
11835 }
11836
11837 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
11838 E = ULE->decls_end(); I != E; ++I)
11839 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
11840 CandidateSet, PartialOverloading,
11841 /*KnownValid*/ true);
11842
11843 if (ULE->requiresADL())
11844 AddArgumentDependentLookupCandidates(ULE->getName(), ULE->getExprLoc(),
11845 Args, ExplicitTemplateArgs,
11846 CandidateSet, PartialOverloading);
11847}
11848
11849/// Determine whether a declaration with the specified name could be moved into
11850/// a different namespace.
11851static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
11852 switch (Name.getCXXOverloadedOperator()) {
11853 case OO_New: case OO_Array_New:
11854 case OO_Delete: case OO_Array_Delete:
11855 return false;
11856
11857 default:
11858 return true;
11859 }
11860}
11861
11862/// Attempt to recover from an ill-formed use of a non-dependent name in a
11863/// template, where the non-dependent name was declared after the template
11864/// was defined. This is common in code written for a compilers which do not
11865/// correctly implement two-stage name lookup.
11866///
11867/// Returns true if a viable candidate was found and a diagnostic was issued.
11868static bool
11869DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
11870 const CXXScopeSpec &SS, LookupResult &R,
11871 OverloadCandidateSet::CandidateSetKind CSK,
11872 TemplateArgumentListInfo *ExplicitTemplateArgs,
11873 ArrayRef<Expr *> Args,
11874 bool *DoDiagnoseEmptyLookup = nullptr) {
11875 if (!SemaRef.inTemplateInstantiation() || !SS.isEmpty())
11876 return false;
11877
11878 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
11879 if (DC->isTransparentContext())
11880 continue;
11881
11882 SemaRef.LookupQualifiedName(R, DC);
11883
11884 if (!R.empty()) {
11885 R.suppressDiagnostics();
11886
11887 if (isa<CXXRecordDecl>(DC)) {
11888 // Don't diagnose names we find in classes; we get much better
11889 // diagnostics for these from DiagnoseEmptyLookup.
11890 R.clear();
11891 if (DoDiagnoseEmptyLookup)
11892 *DoDiagnoseEmptyLookup = true;
11893 return false;
11894 }
11895
11896 OverloadCandidateSet Candidates(FnLoc, CSK);
11897 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
11898 AddOverloadedCallCandidate(SemaRef, I.getPair(),
11899 ExplicitTemplateArgs, Args,
11900 Candidates, false, /*KnownValid*/ false);
11901
11902 OverloadCandidateSet::iterator Best;
11903 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
11904 // No viable functions. Don't bother the user with notes for functions
11905 // which don't work and shouldn't be found anyway.
11906 R.clear();
11907 return false;
11908 }
11909
11910 // Find the namespaces where ADL would have looked, and suggest
11911 // declaring the function there instead.
11912 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11913 Sema::AssociatedClassSet AssociatedClasses;
11914 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
11915 AssociatedNamespaces,
11916 AssociatedClasses);
11917 Sema::AssociatedNamespaceSet SuggestedNamespaces;
11918 if (canBeDeclaredInNamespace(R.getLookupName())) {
11919 DeclContext *Std = SemaRef.getStdNamespace();
11920 for (Sema::AssociatedNamespaceSet::iterator
11921 it = AssociatedNamespaces.begin(),
11922 end = AssociatedNamespaces.end(); it != end; ++it) {
11923 // Never suggest declaring a function within namespace 'std'.
11924 if (Std && Std->Encloses(*it))
11925 continue;
11926
11927 // Never suggest declaring a function within a namespace with a
11928 // reserved name, like __gnu_cxx.
11929 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
11930 if (NS &&
11931 NS->getQualifiedNameAsString().find("__") != std::string::npos)
11932 continue;
11933
11934 SuggestedNamespaces.insert(*it);
11935 }
11936 }
11937
11938 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
11939 << R.getLookupName();
11940 if (SuggestedNamespaces.empty()) {
11941 SemaRef.Diag(Best->Function->getLocation(),
11942 diag::note_not_found_by_two_phase_lookup)
11943 << R.getLookupName() << 0;
11944 } else if (SuggestedNamespaces.size() == 1) {
11945 SemaRef.Diag(Best->Function->getLocation(),
11946 diag::note_not_found_by_two_phase_lookup)
11947 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
11948 } else {
11949 // FIXME: It would be useful to list the associated namespaces here,
11950 // but the diagnostics infrastructure doesn't provide a way to produce
11951 // a localized representation of a list of items.
11952 SemaRef.Diag(Best->Function->getLocation(),
11953 diag::note_not_found_by_two_phase_lookup)
11954 << R.getLookupName() << 2;
11955 }
11956
11957 // Try to recover by calling this function.
11958 return true;
11959 }
11960
11961 R.clear();
11962 }
11963
11964 return false;
11965}
11966
11967/// Attempt to recover from ill-formed use of a non-dependent operator in a
11968/// template, where the non-dependent operator was declared after the template
11969/// was defined.
11970///
11971/// Returns true if a viable candidate was found and a diagnostic was issued.
11972static bool
11973DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
11974 SourceLocation OpLoc,
11975 ArrayRef<Expr *> Args) {
11976 DeclarationName OpName =
11977 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
11978 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
11979 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
11980 OverloadCandidateSet::CSK_Operator,
11981 /*ExplicitTemplateArgs=*/nullptr, Args);
11982}
11983
11984namespace {
11985class BuildRecoveryCallExprRAII {
11986 Sema &SemaRef;
11987public:
11988 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
11989 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
11990 SemaRef.IsBuildingRecoveryCallExpr = true;
11991 }
11992
11993 ~BuildRecoveryCallExprRAII() {
11994 SemaRef.IsBuildingRecoveryCallExpr = false;
11995 }
11996};
11997
11998}
11999
12000/// Attempts to recover from a call where no functions were found.
12001///
12002/// Returns true if new candidates were found.
12003static ExprResult
12004BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12005 UnresolvedLookupExpr *ULE,
12006 SourceLocation LParenLoc,
12007 MutableArrayRef<Expr *> Args,
12008 SourceLocation RParenLoc,
12009 bool EmptyLookup, bool AllowTypoCorrection) {
12010 // Do not try to recover if it is already building a recovery call.
12011 // This stops infinite loops for template instantiations like
12012 //
12013 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
12014 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
12015 //
12016 if (SemaRef.IsBuildingRecoveryCallExpr)
12017 return ExprError();
12018 BuildRecoveryCallExprRAII RCE(SemaRef);
12019
12020 CXXScopeSpec SS;
12021 SS.Adopt(ULE->getQualifierLoc());
12022 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
12023
12024 TemplateArgumentListInfo TABuffer;
12025 TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr;
12026 if (ULE->hasExplicitTemplateArgs()) {
12027 ULE->copyTemplateArgumentsInto(TABuffer);
12028 ExplicitTemplateArgs = &TABuffer;
12029 }
12030
12031 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
12032 Sema::LookupOrdinaryName);
12033 bool DoDiagnoseEmptyLookup = EmptyLookup;
12034 if (!DiagnoseTwoPhaseLookup(
12035 SemaRef, Fn->getExprLoc(), SS, R, OverloadCandidateSet::CSK_Normal,
12036 ExplicitTemplateArgs, Args, &DoDiagnoseEmptyLookup)) {
12037 NoTypoCorrectionCCC NoTypoValidator{};
12038 FunctionCallFilterCCC FunctionCallValidator(SemaRef, Args.size(),
12039 ExplicitTemplateArgs != nullptr,
12040 dyn_cast<MemberExpr>(Fn));
12041 CorrectionCandidateCallback &Validator =
12042 AllowTypoCorrection
12043 ? static_cast<CorrectionCandidateCallback &>(FunctionCallValidator)
12044 : static_cast<CorrectionCandidateCallback &>(NoTypoValidator);
12045 if (!DoDiagnoseEmptyLookup ||
12046 SemaRef.DiagnoseEmptyLookup(S, SS, R, Validator, ExplicitTemplateArgs,
12047 Args))
12048 return ExprError();
12049 }
12050
12051 assert(!R.empty() && "lookup results empty despite recovery");
12052
12053 // If recovery created an ambiguity, just bail out.
12054 if (R.isAmbiguous()) {
12055 R.suppressDiagnostics();
12056 return ExprError();
12057 }
12058
12059 // Build an implicit member call if appropriate. Just drop the
12060 // casts and such from the call, we don't really care.
12061 ExprResult NewFn = ExprError();
12062 if ((*R.begin())->isCXXClassMember())
12063 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12064 ExplicitTemplateArgs, S);
12065 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
12066 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
12067 ExplicitTemplateArgs);
12068 else
12069 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
12070
12071 if (NewFn.isInvalid())
12072 return ExprError();
12073
12074 // This shouldn't cause an infinite loop because we're giving it
12075 // an expression with viable lookup results, which should never
12076 // end up here.
12077 return SemaRef.BuildCallExpr(/*Scope*/ nullptr, NewFn.get(), LParenLoc,
12078 MultiExprArg(Args.data(), Args.size()),
12079 RParenLoc);
12080}
12081
12082/// Constructs and populates an OverloadedCandidateSet from
12083/// the given function.
12084/// \returns true when an the ExprResult output parameter has been set.
12085bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
12086 UnresolvedLookupExpr *ULE,
12087 MultiExprArg Args,
12088 SourceLocation RParenLoc,
12089 OverloadCandidateSet *CandidateSet,
12090 ExprResult *Result) {
12091#ifndef NDEBUG
12092 if (ULE->requiresADL()) {
12093 // To do ADL, we must have found an unqualified name.
12094 assert(!ULE->getQualifier() && "qualified name with ADL");
12095
12096 // We don't perform ADL for implicit declarations of builtins.
12097 // Verify that this was correctly set up.
12098 FunctionDecl *F;
12099 if (ULE->decls_begin() != ULE->decls_end() &&
12100 ULE->decls_begin() + 1 == ULE->decls_end() &&
12101 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
12102 F->getBuiltinID() && F->isImplicit())
12103 llvm_unreachable("performing ADL for builtin");
12104
12105 // We don't perform ADL in C.
12106 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
12107 }
12108#endif
12109
12110 UnbridgedCastsSet UnbridgedCasts;
12111 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
12112 *Result = ExprError();
12113 return true;
12114 }
12115
12116 // Add the functions denoted by the callee to the set of candidate
12117 // functions, including those from argument-dependent lookup.
12118 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
12119
12120 if (getLangOpts().MSVCCompat &&
12121 CurContext->isDependentContext() && !isSFINAEContext() &&
12122 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
12123
12124 OverloadCandidateSet::iterator Best;
12125 if (CandidateSet->empty() ||
12126 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best) ==
12127 OR_No_Viable_Function) {
12128 // In Microsoft mode, if we are inside a template class member function
12129 // then create a type dependent CallExpr. The goal is to postpone name
12130 // lookup to instantiation time to be able to search into type dependent
12131 // base classes.
12132 CallExpr *CE = CallExpr::Create(Context, Fn, Args, Context.DependentTy,
12133 VK_RValue, RParenLoc);
12134 CE->setTypeDependent(true);
12135 CE->setValueDependent(true);
12136 CE->setInstantiationDependent(true);
12137 *Result = CE;
12138 return true;
12139 }
12140 }
12141
12142 if (CandidateSet->empty())
12143 return false;
12144
12145 UnbridgedCasts.restore();
12146 return false;
12147}
12148
12149/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
12150/// the completed call expression. If overload resolution fails, emits
12151/// diagnostics and returns ExprError()
12152static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
12153 UnresolvedLookupExpr *ULE,
12154 SourceLocation LParenLoc,
12155 MultiExprArg Args,
12156 SourceLocation RParenLoc,
12157 Expr *ExecConfig,
12158 OverloadCandidateSet *CandidateSet,
12159 OverloadCandidateSet::iterator *Best,
12160 OverloadingResult OverloadResult,
12161 bool AllowTypoCorrection) {
12162 if (CandidateSet->empty())
12163 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
12164 RParenLoc, /*EmptyLookup=*/true,
12165 AllowTypoCorrection);
12166
12167 switch (OverloadResult) {
12168 case OR_Success: {
12169 FunctionDecl *FDecl = (*Best)->Function;
12170 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
12171 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
12172 return ExprError();
12173 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12174 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12175 ExecConfig, /*IsExecConfig=*/false,
12176 (*Best)->IsADLCandidate);
12177 }
12178
12179 case OR_No_Viable_Function: {
12180 // Try to recover by looking for viable functions which the user might
12181 // have meant to call.
12182 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
12183 Args, RParenLoc,
12184 /*EmptyLookup=*/false,
12185 AllowTypoCorrection);
12186 if (!Recovery.isInvalid())
12187 return Recovery;
12188
12189 // If the user passes in a function that we can't take the address of, we
12190 // generally end up emitting really bad error messages. Here, we attempt to
12191 // emit better ones.
12192 for (const Expr *Arg : Args) {
12193 if (!Arg->getType()->isFunctionType())
12194 continue;
12195 if (auto *DRE = dyn_cast<DeclRefExpr>(Arg->IgnoreParenImpCasts())) {
12196 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
12197 if (FD &&
12198 !SemaRef.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true,
12199 Arg->getExprLoc()))
12200 return ExprError();
12201 }
12202 }
12203
12204 CandidateSet->NoteCandidates(
12205 PartialDiagnosticAt(
12206 Fn->getBeginLoc(),
12207 SemaRef.PDiag(diag::err_ovl_no_viable_function_in_call)
12208 << ULE->getName() << Fn->getSourceRange()),
12209 SemaRef, OCD_AllCandidates, Args);
12210 break;
12211 }
12212
12213 case OR_Ambiguous:
12214 CandidateSet->NoteCandidates(
12215 PartialDiagnosticAt(Fn->getBeginLoc(),
12216 SemaRef.PDiag(diag::err_ovl_ambiguous_call)
12217 << ULE->getName() << Fn->getSourceRange()),
12218 SemaRef, OCD_ViableCandidates, Args);
12219 break;
12220
12221 case OR_Deleted: {
12222 CandidateSet->NoteCandidates(
12223 PartialDiagnosticAt(Fn->getBeginLoc(),
12224 SemaRef.PDiag(diag::err_ovl_deleted_call)
12225 << ULE->getName() << Fn->getSourceRange()),
12226 SemaRef, OCD_AllCandidates, Args);
12227
12228 // We emitted an error for the unavailable/deleted function call but keep
12229 // the call in the AST.
12230 FunctionDecl *FDecl = (*Best)->Function;
12231 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
12232 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
12233 ExecConfig, /*IsExecConfig=*/false,
12234 (*Best)->IsADLCandidate);
12235 }
12236 }
12237
12238 // Overload resolution failed.
12239 return ExprError();
12240}
12241
12242static void markUnaddressableCandidatesUnviable(Sema &S,
12243 OverloadCandidateSet &CS) {
12244 for (auto I = CS.begin(), E = CS.end(); I != E; ++I) {
12245 if (I->Viable &&
12246 !S.checkAddressOfFunctionIsAvailable(I->Function, /*Complain=*/false)) {
12247 I->Viable = false;
12248 I->FailureKind = ovl_fail_addr_not_available;
12249 }
12250 }
12251}
12252
12253/// BuildOverloadedCallExpr - Given the call expression that calls Fn
12254/// (which eventually refers to the declaration Func) and the call
12255/// arguments Args/NumArgs, attempt to resolve the function call down
12256/// to a specific function. If overload resolution succeeds, returns
12257/// the call expression produced by overload resolution.
12258/// Otherwise, emits diagnostics and returns ExprError.
12259ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
12260 UnresolvedLookupExpr *ULE,
12261 SourceLocation LParenLoc,
12262 MultiExprArg Args,
12263 SourceLocation RParenLoc,
12264 Expr *ExecConfig,
12265 bool AllowTypoCorrection,
12266 bool CalleesAddressIsTaken) {
12267 OverloadCandidateSet CandidateSet(Fn->getExprLoc(),
12268 OverloadCandidateSet::CSK_Normal);
12269 ExprResult result;
12270
12271 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
12272 &result))
12273 return result;
12274
12275 // If the user handed us something like `(&Foo)(Bar)`, we need to ensure that
12276 // functions that aren't addressible are considered unviable.
12277 if (CalleesAddressIsTaken)
12278 markUnaddressableCandidatesUnviable(*this, CandidateSet);
12279
12280 OverloadCandidateSet::iterator Best;
12281 OverloadingResult OverloadResult =
12282 CandidateSet.BestViableFunction(*this, Fn->getBeginLoc(), Best);
12283
12284 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, RParenLoc,
12285 ExecConfig, &CandidateSet, &Best,
12286 OverloadResult, AllowTypoCorrection);
12287}
12288
12289static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
12290 return Functions.size() > 1 ||
12291 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
12292}
12293
12294/// Create a unary operation that may resolve to an overloaded
12295/// operator.
12296///
12297/// \param OpLoc The location of the operator itself (e.g., '*').
12298///
12299/// \param Opc The UnaryOperatorKind that describes this operator.
12300///
12301/// \param Fns The set of non-member functions that will be
12302/// considered by overload resolution. The caller needs to build this
12303/// set based on the context using, e.g.,
12304/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12305/// set should not contain any member functions; those will be added
12306/// by CreateOverloadedUnaryOp().
12307///
12308/// \param Input The input argument.
12309ExprResult
12310Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc,
12311 const UnresolvedSetImpl &Fns,
12312 Expr *Input, bool PerformADL) {
12313 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
12314 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
12315 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12316 // TODO: provide better source location info.
12317 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12318
12319 if (checkPlaceholderForOverload(*this, Input))
12320 return ExprError();
12321
12322 Expr *Args[2] = { Input, nullptr };
12323 unsigned NumArgs = 1;
12324
12325 // For post-increment and post-decrement, add the implicit '0' as
12326 // the second argument, so that we know this is a post-increment or
12327 // post-decrement.
12328 if (Opc == UO_PostInc || Opc == UO_PostDec) {
12329 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
12330 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
12331 SourceLocation());
12332 NumArgs = 2;
12333 }
12334
12335 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
12336
12337 if (Input->isTypeDependent()) {
12338 if (Fns.empty())
12339 return new (Context) UnaryOperator(Input, Opc, Context.DependentTy,
12340 VK_RValue, OK_Ordinary, OpLoc, false);
12341
12342 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12343 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12344 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12345 /*ADL*/ true, IsOverloaded(Fns), Fns.begin(), Fns.end());
12346 return CXXOperatorCallExpr::Create(Context, Op, Fn, ArgsArray,
12347 Context.DependentTy, VK_RValue, OpLoc,
12348 FPOptions());
12349 }
12350
12351 // Build an empty overload set.
12352 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12353
12354 // Add the candidates from the given function set.
12355 AddFunctionCandidates(Fns, ArgsArray, CandidateSet);
12356
12357 // Add operator candidates that are member functions.
12358 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12359
12360 // Add candidates from ADL.
12361 if (PerformADL) {
12362 AddArgumentDependentLookupCandidates(OpName, OpLoc, ArgsArray,
12363 /*ExplicitTemplateArgs*/nullptr,
12364 CandidateSet);
12365 }
12366
12367 // Add builtin operator candidates.
12368 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
12369
12370 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12371
12372 // Perform overload resolution.
12373 OverloadCandidateSet::iterator Best;
12374 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12375 case OR_Success: {
12376 // We found a built-in operator or an overloaded operator.
12377 FunctionDecl *FnDecl = Best->Function;
12378
12379 if (FnDecl) {
12380 Expr *Base = nullptr;
12381 // We matched an overloaded operator. Build a call to that
12382 // operator.
12383
12384 // Convert the arguments.
12385 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12386 CheckMemberOperatorAccess(OpLoc, Args[0], nullptr, Best->FoundDecl);
12387
12388 ExprResult InputRes =
12389 PerformObjectArgumentInitialization(Input, /*Qualifier=*/nullptr,
12390 Best->FoundDecl, Method);
12391 if (InputRes.isInvalid())
12392 return ExprError();
12393 Base = Input = InputRes.get();
12394 } else {
12395 // Convert the arguments.
12396 ExprResult InputInit
12397 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12398 Context,
12399 FnDecl->getParamDecl(0)),
12400 SourceLocation(),
12401 Input);
12402 if (InputInit.isInvalid())
12403 return ExprError();
12404 Input = InputInit.get();
12405 }
12406
12407 // Build the actual expression node.
12408 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
12409 Base, HadMultipleCandidates,
12410 OpLoc);
12411 if (FnExpr.isInvalid())
12412 return ExprError();
12413
12414 // Determine the result type.
12415 QualType ResultTy = FnDecl->getReturnType();
12416 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12417 ResultTy = ResultTy.getNonLValueExprType(Context);
12418
12419 Args[0] = Input;
12420 CallExpr *TheCall = CXXOperatorCallExpr::Create(
12421 Context, Op, FnExpr.get(), ArgsArray, ResultTy, VK, OpLoc,
12422 FPOptions(), Best->IsADLCandidate);
12423
12424 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
12425 return ExprError();
12426
12427 if (CheckFunctionCall(FnDecl, TheCall,
12428 FnDecl->getType()->castAs<FunctionProtoType>()))
12429 return ExprError();
12430
12431 return MaybeBindToTemporary(TheCall);
12432 } else {
12433 // We matched a built-in operator. Convert the arguments, then
12434 // break out so that we will build the appropriate built-in
12435 // operator node.
12436 ExprResult InputRes = PerformImplicitConversion(
12437 Input, Best->BuiltinParamTypes[0], Best->Conversions[0], AA_Passing,
12438 CCK_ForBuiltinOverloadedOp);
12439 if (InputRes.isInvalid())
12440 return ExprError();
12441 Input = InputRes.get();
12442 break;
12443 }
12444 }
12445
12446 case OR_No_Viable_Function:
12447 // This is an erroneous use of an operator which can be overloaded by
12448 // a non-member function. Check for non-member operators which were
12449 // defined too late to be candidates.
12450 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
12451 // FIXME: Recover by calling the found function.
12452 return ExprError();
12453
12454 // No viable function; fall through to handling this as a
12455 // built-in operator, which will produce an error message for us.
12456 break;
12457
12458 case OR_Ambiguous:
12459 CandidateSet.NoteCandidates(
12460 PartialDiagnosticAt(OpLoc,
12461 PDiag(diag::err_ovl_ambiguous_oper_unary)
12462 << UnaryOperator::getOpcodeStr(Opc)
12463 << Input->getType() << Input->getSourceRange()),
12464 *this, OCD_ViableCandidates, ArgsArray,
12465 UnaryOperator::getOpcodeStr(Opc), OpLoc);
12466 return ExprError();
12467
12468 case OR_Deleted:
12469 CandidateSet.NoteCandidates(
12470 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12471 << UnaryOperator::getOpcodeStr(Opc)
12472 << Input->getSourceRange()),
12473 *this, OCD_AllCandidates, ArgsArray, UnaryOperator::getOpcodeStr(Opc),
12474 OpLoc);
12475 return ExprError();
12476 }
12477
12478 // Either we found no viable overloaded operator or we matched a
12479 // built-in operator. In either case, fall through to trying to
12480 // build a built-in operation.
12481 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
12482}
12483
12484/// Create a binary operation that may resolve to an overloaded
12485/// operator.
12486///
12487/// \param OpLoc The location of the operator itself (e.g., '+').
12488///
12489/// \param Opc The BinaryOperatorKind that describes this operator.
12490///
12491/// \param Fns The set of non-member functions that will be
12492/// considered by overload resolution. The caller needs to build this
12493/// set based on the context using, e.g.,
12494/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
12495/// set should not contain any member functions; those will be added
12496/// by CreateOverloadedBinOp().
12497///
12498/// \param LHS Left-hand argument.
12499/// \param RHS Right-hand argument.
12500ExprResult
12501Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
12502 BinaryOperatorKind Opc,
12503 const UnresolvedSetImpl &Fns,
12504 Expr *LHS, Expr *RHS, bool PerformADL) {
12505 Expr *Args[2] = { LHS, RHS };
12506 LHS=RHS=nullptr; // Please use only Args instead of LHS/RHS couple
12507
12508 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
12509 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
12510
12511 // If either side is type-dependent, create an appropriate dependent
12512 // expression.
12513 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12514 if (Fns.empty()) {
12515 // If there are no functions to store, just build a dependent
12516 // BinaryOperator or CompoundAssignment.
12517 if (Opc <= BO_Assign || Opc > BO_OrAssign)
12518 return new (Context) BinaryOperator(
12519 Args[0], Args[1], Opc, Context.DependentTy, VK_RValue, OK_Ordinary,
12520 OpLoc, FPFeatures);
12521
12522 return new (Context) CompoundAssignOperator(
12523 Args[0], Args[1], Opc, Context.DependentTy, VK_LValue, OK_Ordinary,
12524 Context.DependentTy, Context.DependentTy, OpLoc,
12525 FPFeatures);
12526 }
12527
12528 // FIXME: save results of ADL from here?
12529 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12530 // TODO: provide better source location info in DNLoc component.
12531 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
12532 UnresolvedLookupExpr *Fn = UnresolvedLookupExpr::Create(
12533 Context, NamingClass, NestedNameSpecifierLoc(), OpNameInfo,
12534 /*ADL*/ PerformADL, IsOverloaded(Fns), Fns.begin(), Fns.end());
12535 return CXXOperatorCallExpr::Create(Context, Op, Fn, Args,
12536 Context.DependentTy, VK_RValue, OpLoc,
12537 FPFeatures);
12538 }
12539
12540 // Always do placeholder-like conversions on the RHS.
12541 if (checkPlaceholderForOverload(*this, Args[1]))
12542 return ExprError();
12543
12544 // Do placeholder-like conversion on the LHS; note that we should
12545 // not get here with a PseudoObject LHS.
12546 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
12547 if (checkPlaceholderForOverload(*this, Args[0]))
12548 return ExprError();
12549
12550 // If this is the assignment operator, we only perform overload resolution
12551 // if the left-hand side is a class or enumeration type. This is actually
12552 // a hack. The standard requires that we do overload resolution between the
12553 // various built-in candidates, but as DR507 points out, this can lead to
12554 // problems. So we do it this way, which pretty much follows what GCC does.
12555 // Note that we go the traditional code path for compound assignment forms.
12556 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
12557 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12558
12559 // If this is the .* operator, which is not overloadable, just
12560 // create a built-in binary operator.
12561 if (Opc == BO_PtrMemD)
12562 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12563
12564 // Build an empty overload set.
12565 OverloadCandidateSet CandidateSet(OpLoc, OverloadCandidateSet::CSK_Operator);
12566
12567 // Add the candidates from the given function set.
12568 AddFunctionCandidates(Fns, Args, CandidateSet);
12569
12570 // Add operator candidates that are member functions.
12571 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12572
12573 // Add candidates from ADL. Per [over.match.oper]p2, this lookup is not
12574 // performed for an assignment operator (nor for operator[] nor operator->,
12575 // which don't get here).
12576 if (Opc != BO_Assign && PerformADL)
12577 AddArgumentDependentLookupCandidates(OpName, OpLoc, Args,
12578 /*ExplicitTemplateArgs*/ nullptr,
12579 CandidateSet);
12580
12581 // Add builtin operator candidates.
12582 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
12583
12584 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12585
12586 // Perform overload resolution.
12587 OverloadCandidateSet::iterator Best;
12588 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
12589 case OR_Success: {
12590 // We found a built-in operator or an overloaded operator.
12591 FunctionDecl *FnDecl = Best->Function;
12592
12593 if (FnDecl) {
12594 Expr *Base = nullptr;
12595 // We matched an overloaded operator. Build a call to that
12596 // operator.
12597
12598 // Convert the arguments.
12599 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
12600 // Best->Access is only meaningful for class members.
12601 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
12602
12603 ExprResult Arg1 =
12604 PerformCopyInitialization(
12605 InitializedEntity::InitializeParameter(Context,
12606 FnDecl->getParamDecl(0)),
12607 SourceLocation(), Args[1]);
12608 if (Arg1.isInvalid())
12609 return ExprError();
12610
12611 ExprResult Arg0 =
12612 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12613 Best->FoundDecl, Method);
12614 if (Arg0.isInvalid())
12615 return ExprError();
12616 Base = Args[0] = Arg0.getAs<Expr>();
12617 Args[1] = RHS = Arg1.getAs<Expr>();
12618 } else {
12619 // Convert the arguments.
12620 ExprResult Arg0 = PerformCopyInitialization(
12621 InitializedEntity::InitializeParameter(Context,
12622 FnDecl->getParamDecl(0)),
12623 SourceLocation(), Args[0]);
12624 if (Arg0.isInvalid())
12625 return ExprError();
12626
12627 ExprResult Arg1 =
12628 PerformCopyInitialization(
12629 InitializedEntity::InitializeParameter(Context,
12630 FnDecl->getParamDecl(1)),
12631 SourceLocation(), Args[1]);
12632 if (Arg1.isInvalid())
12633 return ExprError();
12634 Args[0] = LHS = Arg0.getAs<Expr>();
12635 Args[1] = RHS = Arg1.getAs<Expr>();
12636 }
12637
12638 // Build the actual expression node.
12639 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12640 Best->FoundDecl, Base,
12641 HadMultipleCandidates, OpLoc);
12642 if (FnExpr.isInvalid())
12643 return ExprError();
12644
12645 // Determine the result type.
12646 QualType ResultTy = FnDecl->getReturnType();
12647 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12648 ResultTy = ResultTy.getNonLValueExprType(Context);
12649
12650 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
12651 Context, Op, FnExpr.get(), Args, ResultTy, VK, OpLoc, FPFeatures,
12652 Best->IsADLCandidate);
12653
12654 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
12655 FnDecl))
12656 return ExprError();
12657
12658 ArrayRef<const Expr *> ArgsArray(Args, 2);
12659 const Expr *ImplicitThis = nullptr;
12660 // Cut off the implicit 'this'.
12661 if (isa<CXXMethodDecl>(FnDecl)) {
12662 ImplicitThis = ArgsArray[0];
12663 ArgsArray = ArgsArray.slice(1);
12664 }
12665
12666 // Check for a self move.
12667 if (Op == OO_Equal)
12668 DiagnoseSelfMove(Args[0], Args[1], OpLoc);
12669
12670 checkCall(FnDecl, nullptr, ImplicitThis, ArgsArray,
12671 isa<CXXMethodDecl>(FnDecl), OpLoc, TheCall->getSourceRange(),
12672 VariadicDoesNotApply);
12673
12674 return MaybeBindToTemporary(TheCall);
12675 } else {
12676 // We matched a built-in operator. Convert the arguments, then
12677 // break out so that we will build the appropriate built-in
12678 // operator node.
12679 ExprResult ArgsRes0 = PerformImplicitConversion(
12680 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12681 AA_Passing, CCK_ForBuiltinOverloadedOp);
12682 if (ArgsRes0.isInvalid())
12683 return ExprError();
12684 Args[0] = ArgsRes0.get();
12685
12686 ExprResult ArgsRes1 = PerformImplicitConversion(
12687 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12688 AA_Passing, CCK_ForBuiltinOverloadedOp);
12689 if (ArgsRes1.isInvalid())
12690 return ExprError();
12691 Args[1] = ArgsRes1.get();
12692 break;
12693 }
12694 }
12695
12696 case OR_No_Viable_Function: {
12697 // C++ [over.match.oper]p9:
12698 // If the operator is the operator , [...] and there are no
12699 // viable functions, then the operator is assumed to be the
12700 // built-in operator and interpreted according to clause 5.
12701 if (Opc == BO_Comma)
12702 break;
12703
12704 // For class as left operand for assignment or compound assignment
12705 // operator do not fall through to handling in built-in, but report that
12706 // no overloaded assignment operator found
12707 ExprResult Result = ExprError();
12708 StringRef OpcStr = BinaryOperator::getOpcodeStr(Opc);
12709 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates,
12710 Args, OpLoc);
12711 if (Args[0]->getType()->isRecordType() &&
12712 Opc >= BO_Assign && Opc <= BO_OrAssign) {
12713 Diag(OpLoc, diag::err_ovl_no_viable_oper)
12714 << BinaryOperator::getOpcodeStr(Opc)
12715 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12716 if (Args[0]->getType()->isIncompleteType()) {
12717 Diag(OpLoc, diag::note_assign_lhs_incomplete)
12718 << Args[0]->getType()
12719 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
12720 }
12721 } else {
12722 // This is an erroneous use of an operator which can be overloaded by
12723 // a non-member function. Check for non-member operators which were
12724 // defined too late to be candidates.
12725 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
12726 // FIXME: Recover by calling the found function.
12727 return ExprError();
12728
12729 // No viable function; try to create a built-in operation, which will
12730 // produce an error. Then, show the non-viable candidates.
12731 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12732 }
12733 assert(Result.isInvalid() &&
12734 "C++ binary operator overloading is missing candidates!");
12735 CandidateSet.NoteCandidates(*this, Args, Cands, OpcStr, OpLoc);
12736 return Result;
12737 }
12738
12739 case OR_Ambiguous:
12740 CandidateSet.NoteCandidates(
12741 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12742 << BinaryOperator::getOpcodeStr(Opc)
12743 << Args[0]->getType()
12744 << Args[1]->getType()
12745 << Args[0]->getSourceRange()
12746 << Args[1]->getSourceRange()),
12747 *this, OCD_ViableCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12748 OpLoc);
12749 return ExprError();
12750
12751 case OR_Deleted:
12752 if (isImplicitlyDeleted(Best->Function)) {
12753 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
12754 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
12755 << Context.getRecordType(Method->getParent())
12756 << getSpecialMember(Method);
12757
12758 // The user probably meant to call this special member. Just
12759 // explain why it's deleted.
12760 NoteDeletedFunction(Method);
12761 return ExprError();
12762 }
12763 CandidateSet.NoteCandidates(
12764 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
12765 << BinaryOperator::getOpcodeStr(Opc)
12766 << Args[0]->getSourceRange()
12767 << Args[1]->getSourceRange()),
12768 *this, OCD_AllCandidates, Args, BinaryOperator::getOpcodeStr(Opc),
12769 OpLoc);
12770 return ExprError();
12771 }
12772
12773 // We matched a built-in operator; build it.
12774 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
12775}
12776
12777ExprResult
12778Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
12779 SourceLocation RLoc,
12780 Expr *Base, Expr *Idx) {
12781 Expr *Args[2] = { Base, Idx };
12782 DeclarationName OpName =
12783 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
12784
12785 // If either side is type-dependent, create an appropriate dependent
12786 // expression.
12787 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
12788
12789 CXXRecordDecl *NamingClass = nullptr; // lookup ignores member operators
12790 // CHECKME: no 'operator' keyword?
12791 DeclarationNameInfo OpNameInfo(OpName, LLoc);
12792 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12793 UnresolvedLookupExpr *Fn
12794 = UnresolvedLookupExpr::Create(Context, NamingClass,
12795 NestedNameSpecifierLoc(), OpNameInfo,
12796 /*ADL*/ true, /*Overloaded*/ false,
12797 UnresolvedSetIterator(),
12798 UnresolvedSetIterator());
12799 // Can't add any actual overloads yet
12800
12801 return CXXOperatorCallExpr::Create(Context, OO_Subscript, Fn, Args,
12802 Context.DependentTy, VK_RValue, RLoc,
12803 FPOptions());
12804 }
12805
12806 // Handle placeholders on both operands.
12807 if (checkPlaceholderForOverload(*this, Args[0]))
12808 return ExprError();
12809 if (checkPlaceholderForOverload(*this, Args[1]))
12810 return ExprError();
12811
12812 // Build an empty overload set.
12813 OverloadCandidateSet CandidateSet(LLoc, OverloadCandidateSet::CSK_Operator);
12814
12815 // Subscript can only be overloaded as a member function.
12816
12817 // Add operator candidates that are member functions.
12818 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12819
12820 // Add builtin operator candidates.
12821 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
12822
12823 bool HadMultipleCandidates = (CandidateSet.size() > 1);
12824
12825 // Perform overload resolution.
12826 OverloadCandidateSet::iterator Best;
12827 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
12828 case OR_Success: {
12829 // We found a built-in operator or an overloaded operator.
12830 FunctionDecl *FnDecl = Best->Function;
12831
12832 if (FnDecl) {
12833 // We matched an overloaded operator. Build a call to that
12834 // operator.
12835
12836 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
12837
12838 // Convert the arguments.
12839 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
12840 ExprResult Arg0 =
12841 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/nullptr,
12842 Best->FoundDecl, Method);
12843 if (Arg0.isInvalid())
12844 return ExprError();
12845 Args[0] = Arg0.get();
12846
12847 // Convert the arguments.
12848 ExprResult InputInit
12849 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
12850 Context,
12851 FnDecl->getParamDecl(0)),
12852 SourceLocation(),
12853 Args[1]);
12854 if (InputInit.isInvalid())
12855 return ExprError();
12856
12857 Args[1] = InputInit.getAs<Expr>();
12858
12859 // Build the actual expression node.
12860 DeclarationNameInfo OpLocInfo(OpName, LLoc);
12861 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
12862 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
12863 Best->FoundDecl,
12864 Base,
12865 HadMultipleCandidates,
12866 OpLocInfo.getLoc(),
12867 OpLocInfo.getInfo());
12868 if (FnExpr.isInvalid())
12869 return ExprError();
12870
12871 // Determine the result type
12872 QualType ResultTy = FnDecl->getReturnType();
12873 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
12874 ResultTy = ResultTy.getNonLValueExprType(Context);
12875
12876 CXXOperatorCallExpr *TheCall =
12877 CXXOperatorCallExpr::Create(Context, OO_Subscript, FnExpr.get(),
12878 Args, ResultTy, VK, RLoc, FPOptions());
12879
12880 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
12881 return ExprError();
12882
12883 if (CheckFunctionCall(Method, TheCall,
12884 Method->getType()->castAs<FunctionProtoType>()))
12885 return ExprError();
12886
12887 return MaybeBindToTemporary(TheCall);
12888 } else {
12889 // We matched a built-in operator. Convert the arguments, then
12890 // break out so that we will build the appropriate built-in
12891 // operator node.
12892 ExprResult ArgsRes0 = PerformImplicitConversion(
12893 Args[0], Best->BuiltinParamTypes[0], Best->Conversions[0],
12894 AA_Passing, CCK_ForBuiltinOverloadedOp);
12895 if (ArgsRes0.isInvalid())
12896 return ExprError();
12897 Args[0] = ArgsRes0.get();
12898
12899 ExprResult ArgsRes1 = PerformImplicitConversion(
12900 Args[1], Best->BuiltinParamTypes[1], Best->Conversions[1],
12901 AA_Passing, CCK_ForBuiltinOverloadedOp);
12902 if (ArgsRes1.isInvalid())
12903 return ExprError();
12904 Args[1] = ArgsRes1.get();
12905
12906 break;
12907 }
12908 }
12909
12910 case OR_No_Viable_Function: {
12911 PartialDiagnostic PD = CandidateSet.empty()
12912 ? (PDiag(diag::err_ovl_no_oper)
12913 << Args[0]->getType() << /*subscript*/ 0
12914 << Args[0]->getSourceRange() << Args[1]->getSourceRange())
12915 : (PDiag(diag::err_ovl_no_viable_subscript)
12916 << Args[0]->getType() << Args[0]->getSourceRange()
12917 << Args[1]->getSourceRange());
12918 CandidateSet.NoteCandidates(PartialDiagnosticAt(LLoc, PD), *this,
12919 OCD_AllCandidates, Args, "[]", LLoc);
12920 return ExprError();
12921 }
12922
12923 case OR_Ambiguous:
12924 CandidateSet.NoteCandidates(
12925 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_ambiguous_oper_binary)
12926 << "[]" << Args[0]->getType()
12927 << Args[1]->getType()
12928 << Args[0]->getSourceRange()
12929 << Args[1]->getSourceRange()),
12930 *this, OCD_ViableCandidates, Args, "[]", LLoc);
12931 return ExprError();
12932
12933 case OR_Deleted:
12934 CandidateSet.NoteCandidates(
12935 PartialDiagnosticAt(LLoc, PDiag(diag::err_ovl_deleted_oper)
12936 << "[]" << Args[0]->getSourceRange()
12937 << Args[1]->getSourceRange()),
12938 *this, OCD_AllCandidates, Args, "[]", LLoc);
12939 return ExprError();
12940 }
12941
12942 // We matched a built-in operator; build it.
12943 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
12944}
12945
12946/// BuildCallToMemberFunction - Build a call to a member
12947/// function. MemExpr is the expression that refers to the member
12948/// function (and includes the object parameter), Args/NumArgs are the
12949/// arguments to the function call (not including the object
12950/// parameter). The caller needs to validate that the member
12951/// expression refers to a non-static member function or an overloaded
12952/// member function.
12953ExprResult
12954Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
12955 SourceLocation LParenLoc,
12956 MultiExprArg Args,
12957 SourceLocation RParenLoc) {
12958 assert(MemExprE->getType() == Context.BoundMemberTy ||
12959 MemExprE->getType() == Context.OverloadTy);
12960
12961 // Dig out the member expression. This holds both the object
12962 // argument and the member function we're referring to.
12963 Expr *NakedMemExpr = MemExprE->IgnoreParens();
12964
12965 // Determine whether this is a call to a pointer-to-member function.
12966 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
12967 assert(op->getType() == Context.BoundMemberTy);
12968 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
12969
12970 QualType fnType =
12971 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
12972
12973 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
12974 QualType resultType = proto->getCallResultType(Context);
12975 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
12976
12977 // Check that the object type isn't more qualified than the
12978 // member function we're calling.
12979 Qualifiers funcQuals = proto->getMethodQuals();
12980
12981 QualType objectType = op->getLHS()->getType();
12982 if (op->getOpcode() == BO_PtrMemI)
12983 objectType = objectType->castAs<PointerType>()->getPointeeType();
12984 Qualifiers objectQuals = objectType.getQualifiers();
12985
12986 Qualifiers difference = objectQuals - funcQuals;
12987 difference.removeObjCGCAttr();
12988 difference.removeAddressSpace();
12989 if (difference) {
12990 std::string qualsString = difference.getAsString();
12991 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
12992 << fnType.getUnqualifiedType()
12993 << qualsString
12994 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
12995 }
12996
12997 CXXMemberCallExpr *call =
12998 CXXMemberCallExpr::Create(Context, MemExprE, Args, resultType,
12999 valueKind, RParenLoc, proto->getNumParams());
13000
13001 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getBeginLoc(),
13002 call, nullptr))
13003 return ExprError();
13004
13005 if (ConvertArgumentsForCall(call, op, nullptr, proto, Args, RParenLoc))
13006 return ExprError();
13007
13008 if (CheckOtherCall(call, proto))
13009 return ExprError();
13010
13011 return MaybeBindToTemporary(call);
13012 }
13013
13014 if (isa<CXXPseudoDestructorExpr>(NakedMemExpr))
13015 return CallExpr::Create(Context, MemExprE, Args, Context.VoidTy, VK_RValue,
13016 RParenLoc);
13017
13018 UnbridgedCastsSet UnbridgedCasts;
13019 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13020 return ExprError();
13021
13022 MemberExpr *MemExpr;
13023 CXXMethodDecl *Method = nullptr;
13024 DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_public);
13025 NestedNameSpecifier *Qualifier = nullptr;
13026 if (isa<MemberExpr>(NakedMemExpr)) {
13027 MemExpr = cast<MemberExpr>(NakedMemExpr);
13028 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
13029 FoundDecl = MemExpr->getFoundDecl();
13030 Qualifier = MemExpr->getQualifier();
13031 UnbridgedCasts.restore();
13032 } else {
13033 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
13034 Qualifier = UnresExpr->getQualifier();
13035
13036 QualType ObjectType = UnresExpr->getBaseType();
13037 Expr::Classification ObjectClassification
13038 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
13039 : UnresExpr->getBase()->Classify(Context);
13040
13041 // Add overload candidates
13042 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc(),
13043 OverloadCandidateSet::CSK_Normal);
13044
13045 // FIXME: avoid copy.
13046 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13047 if (UnresExpr->hasExplicitTemplateArgs()) {
13048 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13049 TemplateArgs = &TemplateArgsBuffer;
13050 }
13051
13052 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
13053 E = UnresExpr->decls_end(); I != E; ++I) {
13054
13055 NamedDecl *Func = *I;
13056 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
13057 if (isa<UsingShadowDecl>(Func))
13058 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
13059
13060
13061 // Microsoft supports direct constructor calls.
13062 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
13063 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args,
13064 CandidateSet,
13065 /*SuppressUserConversions*/ false);
13066 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
13067 // If explicit template arguments were provided, we can't call a
13068 // non-template member function.
13069 if (TemplateArgs)
13070 continue;
13071
13072 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
13073 ObjectClassification, Args, CandidateSet,
13074 /*SuppressUserConversions=*/false);
13075 } else {
13076 AddMethodTemplateCandidate(
13077 cast<FunctionTemplateDecl>(Func), I.getPair(), ActingDC,
13078 TemplateArgs, ObjectType, ObjectClassification, Args, CandidateSet,
13079 /*SuppressUsedConversions=*/false);
13080 }
13081 }
13082
13083 DeclarationName DeclName = UnresExpr->getMemberName();
13084
13085 UnbridgedCasts.restore();
13086
13087 OverloadCandidateSet::iterator Best;
13088 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getBeginLoc(),
13089 Best)) {
13090 case OR_Success:
13091 Method = cast<CXXMethodDecl>(Best->Function);
13092 FoundDecl = Best->FoundDecl;
13093 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
13094 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
13095 return ExprError();
13096 // If FoundDecl is different from Method (such as if one is a template
13097 // and the other a specialization), make sure DiagnoseUseOfDecl is
13098 // called on both.
13099 // FIXME: This would be more comprehensively addressed by modifying
13100 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
13101 // being used.
13102 if (Method != FoundDecl.getDecl() &&
13103 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
13104 return ExprError();
13105 break;
13106
13107 case OR_No_Viable_Function:
13108 CandidateSet.NoteCandidates(
13109 PartialDiagnosticAt(
13110 UnresExpr->getMemberLoc(),
13111 PDiag(diag::err_ovl_no_viable_member_function_in_call)
13112 << DeclName << MemExprE->getSourceRange()),
13113 *this, OCD_AllCandidates, Args);
13114 // FIXME: Leaking incoming expressions!
13115 return ExprError();
13116
13117 case OR_Ambiguous:
13118 CandidateSet.NoteCandidates(
13119 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13120 PDiag(diag::err_ovl_ambiguous_member_call)
13121 << DeclName << MemExprE->getSourceRange()),
13122 *this, OCD_AllCandidates, Args);
13123 // FIXME: Leaking incoming expressions!
13124 return ExprError();
13125
13126 case OR_Deleted:
13127 CandidateSet.NoteCandidates(
13128 PartialDiagnosticAt(UnresExpr->getMemberLoc(),
13129 PDiag(diag::err_ovl_deleted_member_call)
13130 << DeclName << MemExprE->getSourceRange()),
13131 *this, OCD_AllCandidates, Args);
13132 // FIXME: Leaking incoming expressions!
13133 return ExprError();
13134 }
13135
13136 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
13137
13138 // If overload resolution picked a static member, build a
13139 // non-member call based on that function.
13140 if (Method->isStatic()) {
13141 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
13142 RParenLoc);
13143 }
13144
13145 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
13146 }
13147
13148 QualType ResultType = Method->getReturnType();
13149 ExprValueKind VK = Expr::getValueKindForType(ResultType);
13150 ResultType = ResultType.getNonLValueExprType(Context);
13151
13152 assert(Method && "Member call to something that isn't a method?");
13153 const auto *Proto = Method->getType()->getAs<FunctionProtoType>();
13154 CXXMemberCallExpr *TheCall =
13155 CXXMemberCallExpr::Create(Context, MemExprE, Args, ResultType, VK,
13156 RParenLoc, Proto->getNumParams());
13157
13158 // Check for a valid return type.
13159 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
13160 TheCall, Method))
13161 return ExprError();
13162
13163 // Convert the object argument (for a non-static member function call).
13164 // We only need to do this if there was actually an overload; otherwise
13165 // it was done at lookup.
13166 if (!Method->isStatic()) {
13167 ExprResult ObjectArg =
13168 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
13169 FoundDecl, Method);
13170 if (ObjectArg.isInvalid())
13171 return ExprError();
13172 MemExpr->setBase(ObjectArg.get());
13173 }
13174
13175 // Convert the rest of the arguments
13176 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
13177 RParenLoc))
13178 return ExprError();
13179
13180 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13181
13182 if (CheckFunctionCall(Method, TheCall, Proto))
13183 return ExprError();
13184
13185 // In the case the method to call was not selected by the overloading
13186 // resolution process, we still need to handle the enable_if attribute. Do
13187 // that here, so it will not hide previous -- and more relevant -- errors.
13188 if (auto *MemE = dyn_cast<MemberExpr>(NakedMemExpr)) {
13189 if (const EnableIfAttr *Attr = CheckEnableIf(Method, Args, true)) {
13190 Diag(MemE->getMemberLoc(),
13191 diag::err_ovl_no_viable_member_function_in_call)
13192 << Method << Method->getSourceRange();
13193 Diag(Method->getLocation(),
13194 diag::note_ovl_candidate_disabled_by_function_cond_attr)
13195 << Attr->getCond()->getSourceRange() << Attr->getMessage();
13196 return ExprError();
13197 }
13198 }
13199
13200 if ((isa<CXXConstructorDecl>(CurContext) ||
13201 isa<CXXDestructorDecl>(CurContext)) &&
13202 TheCall->getMethodDecl()->isPure()) {
13203 const CXXMethodDecl *MD = TheCall->getMethodDecl();
13204
13205 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts()) &&
13206 MemExpr->performsVirtualDispatch(getLangOpts())) {
13207 Diag(MemExpr->getBeginLoc(),
13208 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
13209 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
13210 << MD->getParent()->getDeclName();
13211
13212 Diag(MD->getBeginLoc(), diag::note_previous_decl) << MD->getDeclName();
13213 if (getLangOpts().AppleKext)
13214 Diag(MemExpr->getBeginLoc(), diag::note_pure_qualified_call_kext)
13215 << MD->getParent()->getDeclName() << MD->getDeclName();
13216 }
13217 }
13218
13219 if (CXXDestructorDecl *DD =
13220 dyn_cast<CXXDestructorDecl>(TheCall->getMethodDecl())) {
13221 // a->A::f() doesn't go through the vtable, except in AppleKext mode.
13222 bool CallCanBeVirtual = !MemExpr->hasQualifier() || getLangOpts().AppleKext;
13223 CheckVirtualDtorCall(DD, MemExpr->getBeginLoc(), /*IsDelete=*/false,
13224 CallCanBeVirtual, /*WarnOnNonAbstractTypes=*/true,
13225 MemExpr->getMemberLoc());
13226 }
13227
13228 return MaybeBindToTemporary(TheCall);
13229}
13230
13231/// BuildCallToObjectOfClassType - Build a call to an object of class
13232/// type (C++ [over.call.object]), which can end up invoking an
13233/// overloaded function call operator (@c operator()) or performing a
13234/// user-defined conversion on the object argument.
13235ExprResult
13236Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
13237 SourceLocation LParenLoc,
13238 MultiExprArg Args,
13239 SourceLocation RParenLoc) {
13240 if (checkPlaceholderForOverload(*this, Obj))
13241 return ExprError();
13242 ExprResult Object = Obj;
13243
13244 UnbridgedCastsSet UnbridgedCasts;
13245 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
13246 return ExprError();
13247
13248 assert(Object.get()->getType()->isRecordType() &&
13249 "Requires object type argument");
13250 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
13251
13252 // C++ [over.call.object]p1:
13253 // If the primary-expression E in the function call syntax
13254 // evaluates to a class object of type "cv T", then the set of
13255 // candidate functions includes at least the function call
13256 // operators of T. The function call operators of T are obtained by
13257 // ordinary lookup of the name operator() in the context of
13258 // (E).operator().
13259 OverloadCandidateSet CandidateSet(LParenLoc,
13260 OverloadCandidateSet::CSK_Operator);
13261 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
13262
13263 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
13264 diag::err_incomplete_object_call, Object.get()))
13265 return true;
13266
13267 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
13268 LookupQualifiedName(R, Record->getDecl());
13269 R.suppressDiagnostics();
13270
13271 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13272 Oper != OperEnd; ++Oper) {
13273 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
13274 Object.get()->Classify(Context), Args, CandidateSet,
13275 /*SuppressUserConversions=*/false);
13276 }
13277
13278 // C++ [over.call.object]p2:
13279 // In addition, for each (non-explicit in C++0x) conversion function
13280 // declared in T of the form
13281 //
13282 // operator conversion-type-id () cv-qualifier;
13283 //
13284 // where cv-qualifier is the same cv-qualification as, or a
13285 // greater cv-qualification than, cv, and where conversion-type-id
13286 // denotes the type "pointer to function of (P1,...,Pn) returning
13287 // R", or the type "reference to pointer to function of
13288 // (P1,...,Pn) returning R", or the type "reference to function
13289 // of (P1,...,Pn) returning R", a surrogate call function [...]
13290 // is also considered as a candidate function. Similarly,
13291 // surrogate call functions are added to the set of candidate
13292 // functions for each conversion function declared in an
13293 // accessible base class provided the function is not hidden
13294 // within T by another intervening declaration.
13295 const auto &Conversions =
13296 cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
13297 for (auto I = Conversions.begin(), E = Conversions.end(); I != E; ++I) {
13298 NamedDecl *D = *I;
13299 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
13300 if (isa<UsingShadowDecl>(D))
13301 D = cast<UsingShadowDecl>(D)->getTargetDecl();
13302
13303 // Skip over templated conversion functions; they aren't
13304 // surrogates.
13305 if (isa<FunctionTemplateDecl>(D))
13306 continue;
13307
13308 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
13309 if (!Conv->isExplicit()) {
13310 // Strip the reference type (if any) and then the pointer type (if
13311 // any) to get down to what might be a function type.
13312 QualType ConvType = Conv->getConversionType().getNonReferenceType();
13313 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
13314 ConvType = ConvPtrType->getPointeeType();
13315
13316 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
13317 {
13318 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
13319 Object.get(), Args, CandidateSet);
13320 }
13321 }
13322 }
13323
13324 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13325
13326 // Perform overload resolution.
13327 OverloadCandidateSet::iterator Best;
13328 switch (CandidateSet.BestViableFunction(*this, Object.get()->getBeginLoc(),
13329 Best)) {
13330 case OR_Success:
13331 // Overload resolution succeeded; we'll build the appropriate call
13332 // below.
13333 break;
13334
13335 case OR_No_Viable_Function: {
13336 PartialDiagnostic PD =
13337 CandidateSet.empty()
13338 ? (PDiag(diag::err_ovl_no_oper)
13339 << Object.get()->getType() << /*call*/ 1
13340 << Object.get()->getSourceRange())
13341 : (PDiag(diag::err_ovl_no_viable_object_call)
13342 << Object.get()->getType() << Object.get()->getSourceRange());
13343 CandidateSet.NoteCandidates(
13344 PartialDiagnosticAt(Object.get()->getBeginLoc(), PD), *this,
13345 OCD_AllCandidates, Args);
13346 break;
13347 }
13348 case OR_Ambiguous:
13349 CandidateSet.NoteCandidates(
13350 PartialDiagnosticAt(Object.get()->getBeginLoc(),
13351 PDiag(diag::err_ovl_ambiguous_object_call)
13352 << Object.get()->getType()
13353 << Object.get()->getSourceRange()),
13354 *this, OCD_ViableCandidates, Args);
13355 break;
13356
13357 case OR_Deleted:
13358 CandidateSet.NoteCandidates(
13359 PartialDiagnosticAt(Object.get()->getBeginLoc(),
13360 PDiag(diag::err_ovl_deleted_object_call)
13361 << Object.get()->getType()
13362 << Object.get()->getSourceRange()),
13363 *this, OCD_AllCandidates, Args);
13364 break;
13365 }
13366
13367 if (Best == CandidateSet.end())
13368 return true;
13369
13370 UnbridgedCasts.restore();
13371
13372 if (Best->Function == nullptr) {
13373 // Since there is no function declaration, this is one of the
13374 // surrogate candidates. Dig out the conversion function.
13375 CXXConversionDecl *Conv
13376 = cast<CXXConversionDecl>(
13377 Best->Conversions[0].UserDefined.ConversionFunction);
13378
13379 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr,
13380 Best->FoundDecl);
13381 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
13382 return ExprError();
13383 assert(Conv == Best->FoundDecl.getDecl() &&
13384 "Found Decl & conversion-to-functionptr should be same, right?!");
13385 // We selected one of the surrogate functions that converts the
13386 // object parameter to a function pointer. Perform the conversion
13387 // on the object argument, then let BuildCallExpr finish the job.
13388
13389 // Create an implicit member expr to refer to the conversion operator.
13390 // and then call it.
13391 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
13392 Conv, HadMultipleCandidates);
13393 if (Call.isInvalid())
13394 return ExprError();
13395 // Record usage of conversion in an implicit cast.
13396 Call = ImplicitCastExpr::Create(Context, Call.get()->getType(),
13397 CK_UserDefinedConversion, Call.get(),
13398 nullptr, VK_RValue);
13399
13400 return BuildCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
13401 }
13402
13403 CheckMemberOperatorAccess(LParenLoc, Object.get(), nullptr, Best->FoundDecl);
13404
13405 // We found an overloaded operator(). Build a CXXOperatorCallExpr
13406 // that calls this method, using Object for the implicit object
13407 // parameter and passing along the remaining arguments.
13408 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13409
13410 // An error diagnostic has already been printed when parsing the declaration.
13411 if (Method->isInvalidDecl())
13412 return ExprError();
13413
13414 const FunctionProtoType *Proto =
13415 Method->getType()->getAs<FunctionProtoType>();
13416
13417 unsigned NumParams = Proto->getNumParams();
13418
13419 DeclarationNameInfo OpLocInfo(
13420 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
13421 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
13422 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13423 Obj, HadMultipleCandidates,
13424 OpLocInfo.getLoc(),
13425 OpLocInfo.getInfo());
13426 if (NewFn.isInvalid())
13427 return true;
13428
13429 // The number of argument slots to allocate in the call. If we have default
13430 // arguments we need to allocate space for them as well. We additionally
13431 // need one more slot for the object parameter.
13432 unsigned NumArgsSlots = 1 + std::max<unsigned>(Args.size(), NumParams);
13433
13434 // Build the full argument list for the method call (the implicit object
13435 // parameter is placed at the beginning of the list).
13436 SmallVector<Expr *, 8> MethodArgs(NumArgsSlots);
13437
13438 bool IsError = false;
13439
13440 // Initialize the implicit object parameter.
13441 ExprResult ObjRes =
13442 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/nullptr,
13443 Best->FoundDecl, Method);
13444 if (ObjRes.isInvalid())
13445 IsError = true;
13446 else
13447 Object = ObjRes;
13448 MethodArgs[0] = Object.get();
13449
13450 // Check the argument types.
13451 for (unsigned i = 0; i != NumParams; i++) {
13452 Expr *Arg;
13453 if (i < Args.size()) {
13454 Arg = Args[i];
13455
13456 // Pass the argument.
13457
13458 ExprResult InputInit
13459 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
13460 Context,
13461 Method->getParamDecl(i)),
13462 SourceLocation(), Arg);
13463
13464 IsError |= InputInit.isInvalid();
13465 Arg = InputInit.getAs<Expr>();
13466 } else {
13467 ExprResult DefArg
13468 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
13469 if (DefArg.isInvalid()) {
13470 IsError = true;
13471 break;
13472 }
13473
13474 Arg = DefArg.getAs<Expr>();
13475 }
13476
13477 MethodArgs[i + 1] = Arg;
13478 }
13479
13480 // If this is a variadic call, handle args passed through "...".
13481 if (Proto->isVariadic()) {
13482 // Promote the arguments (C99 6.5.2.2p7).
13483 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
13484 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod,
13485 nullptr);
13486 IsError |= Arg.isInvalid();
13487 MethodArgs[i + 1] = Arg.get();
13488 }
13489 }
13490
13491 if (IsError)
13492 return true;
13493
13494 DiagnoseSentinelCalls(Method, LParenLoc, Args);
13495
13496 // Once we've built TheCall, all of the expressions are properly owned.
13497 QualType ResultTy = Method->getReturnType();
13498 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13499 ResultTy = ResultTy.getNonLValueExprType(Context);
13500
13501 CXXOperatorCallExpr *TheCall =
13502 CXXOperatorCallExpr::Create(Context, OO_Call, NewFn.get(), MethodArgs,
13503 ResultTy, VK, RParenLoc, FPOptions());
13504
13505 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
13506 return true;
13507
13508 if (CheckFunctionCall(Method, TheCall, Proto))
13509 return true;
13510
13511 return MaybeBindToTemporary(TheCall);
13512}
13513
13514/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
13515/// (if one exists), where @c Base is an expression of class type and
13516/// @c Member is the name of the member we're trying to find.
13517ExprResult
13518Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
13519 bool *NoArrowOperatorFound) {
13520 assert(Base->getType()->isRecordType() &&
13521 "left-hand side must have class type");
13522
13523 if (checkPlaceholderForOverload(*this, Base))
13524 return ExprError();
13525
13526 SourceLocation Loc = Base->getExprLoc();
13527
13528 // C++ [over.ref]p1:
13529 //
13530 // [...] An expression x->m is interpreted as (x.operator->())->m
13531 // for a class object x of type T if T::operator->() exists and if
13532 // the operator is selected as the best match function by the
13533 // overload resolution mechanism (13.3).
13534 DeclarationName OpName =
13535 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
13536 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
13537 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
13538
13539 if (RequireCompleteType(Loc, Base->getType(),
13540 diag::err_typecheck_incomplete_tag, Base))
13541 return ExprError();
13542
13543 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
13544 LookupQualifiedName(R, BaseRecord->getDecl());
13545 R.suppressDiagnostics();
13546
13547 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
13548 Oper != OperEnd; ++Oper) {
13549 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
13550 None, CandidateSet, /*SuppressUserConversions=*/false);
13551 }
13552
13553 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13554
13555 // Perform overload resolution.
13556 OverloadCandidateSet::iterator Best;
13557 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
13558 case OR_Success:
13559 // Overload resolution succeeded; we'll build the call below.
13560 break;
13561
13562 case OR_No_Viable_Function: {
13563 auto Cands = CandidateSet.CompleteCandidates(*this, OCD_AllCandidates, Base);
13564 if (CandidateSet.empty()) {
13565 QualType BaseType = Base->getType();
13566 if (NoArrowOperatorFound) {
13567 // Report this specific error to the caller instead of emitting a
13568 // diagnostic, as requested.
13569 *NoArrowOperatorFound = true;
13570 return ExprError();
13571 }
13572 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
13573 << BaseType << Base->getSourceRange();
13574 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
13575 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
13576 << FixItHint::CreateReplacement(OpLoc, ".");
13577 }
13578 } else
13579 Diag(OpLoc, diag::err_ovl_no_viable_oper)
13580 << "operator->" << Base->getSourceRange();
13581 CandidateSet.NoteCandidates(*this, Base, Cands);
13582 return ExprError();
13583 }
13584 case OR_Ambiguous:
13585 CandidateSet.NoteCandidates(
13586 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_ambiguous_oper_unary)
13587 << "->" << Base->getType()
13588 << Base->getSourceRange()),
13589 *this, OCD_ViableCandidates, Base);
13590 return ExprError();
13591
13592 case OR_Deleted:
13593 CandidateSet.NoteCandidates(
13594 PartialDiagnosticAt(OpLoc, PDiag(diag::err_ovl_deleted_oper)
13595 << "->" << Base->getSourceRange()),
13596 *this, OCD_AllCandidates, Base);
13597 return ExprError();
13598 }
13599
13600 CheckMemberOperatorAccess(OpLoc, Base, nullptr, Best->FoundDecl);
13601
13602 // Convert the object parameter.
13603 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
13604 ExprResult BaseResult =
13605 PerformObjectArgumentInitialization(Base, /*Qualifier=*/nullptr,
13606 Best->FoundDecl, Method);
13607 if (BaseResult.isInvalid())
13608 return ExprError();
13609 Base = BaseResult.get();
13610
13611 // Build the operator call.
13612 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
13613 Base, HadMultipleCandidates, OpLoc);
13614 if (FnExpr.isInvalid())
13615 return ExprError();
13616
13617 QualType ResultTy = Method->getReturnType();
13618 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13619 ResultTy = ResultTy.getNonLValueExprType(Context);
13620 CXXOperatorCallExpr *TheCall = CXXOperatorCallExpr::Create(
13621 Context, OO_Arrow, FnExpr.get(), Base, ResultTy, VK, OpLoc, FPOptions());
13622
13623 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
13624 return ExprError();
13625
13626 if (CheckFunctionCall(Method, TheCall,
13627 Method->getType()->castAs<FunctionProtoType>()))
13628 return ExprError();
13629
13630 return MaybeBindToTemporary(TheCall);
13631}
13632
13633/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
13634/// a literal operator described by the provided lookup results.
13635ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
13636 DeclarationNameInfo &SuffixInfo,
13637 ArrayRef<Expr*> Args,
13638 SourceLocation LitEndLoc,
13639 TemplateArgumentListInfo *TemplateArgs) {
13640 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
13641
13642 OverloadCandidateSet CandidateSet(UDSuffixLoc,
13643 OverloadCandidateSet::CSK_Normal);
13644 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, TemplateArgs,
13645 /*SuppressUserConversions=*/true);
13646
13647 bool HadMultipleCandidates = (CandidateSet.size() > 1);
13648
13649 // Perform overload resolution. This will usually be trivial, but might need
13650 // to perform substitutions for a literal operator template.
13651 OverloadCandidateSet::iterator Best;
13652 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
13653 case OR_Success:
13654 case OR_Deleted:
13655 break;
13656
13657 case OR_No_Viable_Function:
13658 CandidateSet.NoteCandidates(
13659 PartialDiagnosticAt(UDSuffixLoc,
13660 PDiag(diag::err_ovl_no_viable_function_in_call)
13661 << R.getLookupName()),
13662 *this, OCD_AllCandidates, Args);
13663 return ExprError();
13664
13665 case OR_Ambiguous:
13666 CandidateSet.NoteCandidates(
13667 PartialDiagnosticAt(R.getNameLoc(), PDiag(diag::err_ovl_ambiguous_call)
13668 << R.getLookupName()),
13669 *this, OCD_ViableCandidates, Args);
13670 return ExprError();
13671 }
13672
13673 FunctionDecl *FD = Best->Function;
13674 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
13675 nullptr, HadMultipleCandidates,
13676 SuffixInfo.getLoc(),
13677 SuffixInfo.getInfo());
13678 if (Fn.isInvalid())
13679 return true;
13680
13681 // Check the argument types. This should almost always be a no-op, except
13682 // that array-to-pointer decay is applied to string literals.
13683 Expr *ConvArgs[2];
13684 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
13685 ExprResult InputInit = PerformCopyInitialization(
13686 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
13687 SourceLocation(), Args[ArgIdx]);
13688 if (InputInit.isInvalid())
13689 return true;
13690 ConvArgs[ArgIdx] = InputInit.get();
13691 }
13692
13693 QualType ResultTy = FD->getReturnType();
13694 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
13695 ResultTy = ResultTy.getNonLValueExprType(Context);
13696
13697 UserDefinedLiteral *UDL = UserDefinedLiteral::Create(
13698 Context, Fn.get(), llvm::makeArrayRef(ConvArgs, Args.size()), ResultTy,
13699 VK, LitEndLoc, UDSuffixLoc);
13700
13701 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
13702 return ExprError();
13703
13704 if (CheckFunctionCall(FD, UDL, nullptr))
13705 return ExprError();
13706
13707 return MaybeBindToTemporary(UDL);
13708}
13709
13710/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
13711/// given LookupResult is non-empty, it is assumed to describe a member which
13712/// will be invoked. Otherwise, the function will be found via argument
13713/// dependent lookup.
13714/// CallExpr is set to a valid expression and FRS_Success returned on success,
13715/// otherwise CallExpr is set to ExprError() and some non-success value
13716/// is returned.
13717Sema::ForRangeStatus
13718Sema::BuildForRangeBeginEndCall(SourceLocation Loc,
13719 SourceLocation RangeLoc,
13720 const DeclarationNameInfo &NameInfo,
13721 LookupResult &MemberLookup,
13722 OverloadCandidateSet *CandidateSet,
13723 Expr *Range, ExprResult *CallExpr) {
13724 Scope *S = nullptr;
13725
13726 CandidateSet->clear(OverloadCandidateSet::CSK_Normal);
13727 if (!MemberLookup.empty()) {
13728 ExprResult MemberRef =
13729 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
13730 /*IsPtr=*/false, CXXScopeSpec(),
13731 /*TemplateKWLoc=*/SourceLocation(),
13732 /*FirstQualifierInScope=*/nullptr,
13733 MemberLookup,
13734 /*TemplateArgs=*/nullptr, S);
13735 if (MemberRef.isInvalid()) {
13736 *CallExpr = ExprError();
13737 return FRS_DiagnosticIssued;
13738 }
13739 *CallExpr = BuildCallExpr(S, MemberRef.get(), Loc, None, Loc, nullptr);
13740 if (CallExpr->isInvalid()) {
13741 *CallExpr = ExprError();
13742 return FRS_DiagnosticIssued;
13743 }
13744 } else {
13745 UnresolvedSet<0> FoundNames;
13746 UnresolvedLookupExpr *Fn =
13747 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/nullptr,
13748 NestedNameSpecifierLoc(), NameInfo,
13749 /*NeedsADL=*/true, /*Overloaded=*/false,
13750 FoundNames.begin(), FoundNames.end());
13751
13752 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
13753 CandidateSet, CallExpr);
13754 if (CandidateSet->empty() || CandidateSetError) {
13755 *CallExpr = ExprError();
13756 return FRS_NoViableFunction;
13757 }
13758 OverloadCandidateSet::iterator Best;
13759 OverloadingResult OverloadResult =
13760 CandidateSet->BestViableFunction(*this, Fn->getBeginLoc(), Best);
13761
13762 if (OverloadResult == OR_No_Viable_Function) {
13763 *CallExpr = ExprError();
13764 return FRS_NoViableFunction;
13765 }
13766 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
13767 Loc, nullptr, CandidateSet, &Best,
13768 OverloadResult,
13769 /*AllowTypoCorrection=*/false);
13770 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
13771 *CallExpr = ExprError();
13772 return FRS_DiagnosticIssued;
13773 }
13774 }
13775 return FRS_Success;
13776}
13777
13778
13779/// FixOverloadedFunctionReference - E is an expression that refers to
13780/// a C++ overloaded function (possibly with some parentheses and
13781/// perhaps a '&' around it). We have resolved the overloaded function
13782/// to the function declaration Fn, so patch up the expression E to
13783/// refer (possibly indirectly) to Fn. Returns the new expr.
13784Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
13785 FunctionDecl *Fn) {
13786 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
13787 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
13788 Found, Fn);
13789 if (SubExpr == PE->getSubExpr())
13790 return PE;
13791
13792 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
13793 }
13794
13795 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
13796 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
13797 Found, Fn);
13798 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
13799 SubExpr->getType()) &&
13800 "Implicit cast type cannot be determined from overload");
13801 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
13802 if (SubExpr == ICE->getSubExpr())
13803 return ICE;
13804
13805 return ImplicitCastExpr::Create(Context, ICE->getType(),
13806 ICE->getCastKind(),
13807 SubExpr, nullptr,
13808 ICE->getValueKind());
13809 }
13810
13811 if (auto *GSE = dyn_cast<GenericSelectionExpr>(E)) {
13812 if (!GSE->isResultDependent()) {
13813 Expr *SubExpr =
13814 FixOverloadedFunctionReference(GSE->getResultExpr(), Found, Fn);
13815 if (SubExpr == GSE->getResultExpr())
13816 return GSE;
13817
13818 // Replace the resulting type information before rebuilding the generic
13819 // selection expression.
13820 ArrayRef<Expr *> A = GSE->getAssocExprs();
13821 SmallVector<Expr *, 4> AssocExprs(A.begin(), A.end());
13822 unsigned ResultIdx = GSE->getResultIndex();
13823 AssocExprs[ResultIdx] = SubExpr;
13824
13825 return GenericSelectionExpr::Create(
13826 Context, GSE->getGenericLoc(), GSE->getControllingExpr(),
13827 GSE->getAssocTypeSourceInfos(), AssocExprs, GSE->getDefaultLoc(),
13828 GSE->getRParenLoc(), GSE->containsUnexpandedParameterPack(),
13829 ResultIdx);
13830 }
13831 // Rather than fall through to the unreachable, return the original generic
13832 // selection expression.
13833 return GSE;
13834 }
13835
13836 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
13837 assert(UnOp->getOpcode() == UO_AddrOf &&
13838 "Can only take the address of an overloaded function");
13839 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
13840 if (Method->isStatic()) {
13841 // Do nothing: static member functions aren't any different
13842 // from non-member functions.
13843 } else {
13844 // Fix the subexpression, which really has to be an
13845 // UnresolvedLookupExpr holding an overloaded member function
13846 // or template.
13847 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13848 Found, Fn);
13849 if (SubExpr == UnOp->getSubExpr())
13850 return UnOp;
13851
13852 assert(isa<DeclRefExpr>(SubExpr)
13853 && "fixed to something other than a decl ref");
13854 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
13855 && "fixed to a member ref with no nested name qualifier");
13856
13857 // We have taken the address of a pointer to member
13858 // function. Perform the computation here so that we get the
13859 // appropriate pointer to member type.
13860 QualType ClassType
13861 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
13862 QualType MemPtrType
13863 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
13864 // Under the MS ABI, lock down the inheritance model now.
13865 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
13866 (void)isCompleteType(UnOp->getOperatorLoc(), MemPtrType);
13867
13868 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
13869 VK_RValue, OK_Ordinary,
13870 UnOp->getOperatorLoc(), false);
13871 }
13872 }
13873 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
13874 Found, Fn);
13875 if (SubExpr == UnOp->getSubExpr())
13876 return UnOp;
13877
13878 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
13879 Context.getPointerType(SubExpr->getType()),
13880 VK_RValue, OK_Ordinary,
13881 UnOp->getOperatorLoc(), false);
13882 }
13883
13884 // C++ [except.spec]p17:
13885 // An exception-specification is considered to be needed when:
13886 // - in an expression the function is the unique lookup result or the
13887 // selected member of a set of overloaded functions
13888 if (auto *FPT = Fn->getType()->getAs<FunctionProtoType>())
13889 ResolveExceptionSpec(E->getExprLoc(), FPT);
13890
13891 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
13892 // FIXME: avoid copy.
13893 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13894 if (ULE->hasExplicitTemplateArgs()) {
13895 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
13896 TemplateArgs = &TemplateArgsBuffer;
13897 }
13898
13899 DeclRefExpr *DRE =
13900 BuildDeclRefExpr(Fn, Fn->getType(), VK_LValue, ULE->getNameInfo(),
13901 ULE->getQualifierLoc(), Found.getDecl(),
13902 ULE->getTemplateKeywordLoc(), TemplateArgs);
13903 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
13904 return DRE;
13905 }
13906
13907 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
13908 // FIXME: avoid copy.
13909 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
13910 if (MemExpr->hasExplicitTemplateArgs()) {
13911 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
13912 TemplateArgs = &TemplateArgsBuffer;
13913 }
13914
13915 Expr *Base;
13916
13917 // If we're filling in a static method where we used to have an
13918 // implicit member access, rewrite to a simple decl ref.
13919 if (MemExpr->isImplicitAccess()) {
13920 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13921 DeclRefExpr *DRE = BuildDeclRefExpr(
13922 Fn, Fn->getType(), VK_LValue, MemExpr->getNameInfo(),
13923 MemExpr->getQualifierLoc(), Found.getDecl(),
13924 MemExpr->getTemplateKeywordLoc(), TemplateArgs);
13925 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
13926 return DRE;
13927 } else {
13928 SourceLocation Loc = MemExpr->getMemberLoc();
13929 if (MemExpr->getQualifier())
13930 Loc = MemExpr->getQualifierLoc().getBeginLoc();
13931 Base =
13932 BuildCXXThisExpr(Loc, MemExpr->getBaseType(), /*isImplicit=*/true);
13933 }
13934 } else
13935 Base = MemExpr->getBase();
13936
13937 ExprValueKind valueKind;
13938 QualType type;
13939 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
13940 valueKind = VK_LValue;
13941 type = Fn->getType();
13942 } else {
13943 valueKind = VK_RValue;
13944 type = Context.BoundMemberTy;
13945 }
13946
13947 return BuildMemberExpr(
13948 Base, MemExpr->isArrow(), MemExpr->getOperatorLoc(),
13949 MemExpr->getQualifierLoc(), MemExpr->getTemplateKeywordLoc(), Fn, Found,
13950 /*HadMultipleCandidates=*/true, MemExpr->getMemberNameInfo(),
13951 type, valueKind, OK_Ordinary, TemplateArgs);
13952 }
13953
13954 llvm_unreachable("Invalid reference to overloaded function");
13955}
13956
13957ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
13958 DeclAccessPair Found,
13959 FunctionDecl *Fn) {
13960 return FixOverloadedFunctionReference(E.get(), Found, Fn);
13961}
13962